[Django]-Update model django through kwargs

31👍

As long as the PK is the same, the existing row will be overwritten.

obj = Object(index=id, **fields)
obj.save()

19👍

def update_object(obj, **kwargs):
    for k, v in kwargs.items():
        setattr(obj, k, v)
    obj.save()

13👍

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.

10👍

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)
👤leech

8👍

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})
👤ChidG

2👍

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()

0👍

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())

Leave a comment