Reputation: 25585
How can i pass a dict which contain fields to update a Django model? This is not to create an object, but to update it.
example:
obj = Object.objects.create(index=id, **fields)
Upvotes: 31
Views: 28009
Reputation: 2408
Just update the objects dict:
obj.__dict__.update(fields)
obj.save()
Or for extra safety limit the save to only the fields you wish to update.
obj.__dict__.update(fields)
obj.save(update_fields=fields.keys())
Upvotes: 0
Reputation: 3223
This question is a little old, but just to bring it up to date with recent Django developments - since 1.7 there has been an update_or_create
method on querysets which works similarly to get_or_create
.
In this case it could be used like:
obj, created = Object.objects.update_or_create(index=id, defaults={**fields})
Upvotes: 8
Reputation: 20196
you can simply update using methods after filter()
query
obj = Object.objects.filter(index=id).update(**fields) # fields your object(dict) may be **kwargs
if its a .get() method,
obj = Object.objects.get(index=id)
obj['key1'] = 'value1'
obj.save()
Upvotes: 2
Reputation: 8431
If you know you want to create it:
Book.objects.create(**fields)
Assuming you need to check for an existing instance, you can find it with get or create:
instance, created = Book.objects.get_or_create(slug=slug, defaults=fields)
if not created:
for attr, value in fields.iteritems():
setattr(instance, attr, value)
instance.save()
As mentioned in another answer, you can also use the update
function on the queryset manager, but i believe that will not send any signals out (which may not matter to you if you aren't using them). However, you probably shouldn't use it to alter a single object:
Book.objects.filter(id=id).update(**fields)
Upvotes: 10
Reputation: 35639
You can get a queryset of one object, and then update this:
model = Model.objects.filter(pk=pk)
model.update(**kwargs)
This will not call the .save() method on the object, though. I think it will only do one database query, however.
Note that if you didn't filter to one object (ie, the query got multiple objects: such as if you weren't querying on PK) it would update all of them. If it filters to none, then nothing will be written to the database.
Having said that, I wasn't aware of Ignacio's solution. I quite like that.
Upvotes: 13
Reputation: 799250
As long as the PK is the same, the existing row will be overwritten.
obj = Object(index=id, **fields)
obj.save()
Upvotes: 32
Reputation: 375932
def update_object(obj, **kwargs):
for k, v in kwargs.items():
setattr(obj, k, v)
obj.save()
Upvotes: 19