[Django]-How to update multiple fields of a django model instance?

146👍

It’s tempting to mess with __dict__, but that won’t apply to attributes inherited from a parent class.

You can either iterate over the dict to assign to the object:

for (key, value) in my_data_dict.items():
    setattr(obj, key, value)
obj.save()

Or you can directly modify it from a queryset (making sure your query set only returns the object you’re interested in):

FooModel.objects.filter(whatever="anything").update(**my_data_dict)

36👍

You could try this:

obj.__dict__.update(my_data_dict)

4👍

It seems like such a natural thing you’d want to do but like you I’ve not found it in the docs either. The docs do say you should sub-class save() on the model. And that’s what I do.

def save(self, **kwargs):
    mfields = iter(self._meta.fields)
    mods = [(f.attname, kwargs[f.attname]) for f in mfields if f.attname in kwargs]
    for fname, fval in mods: setattr(self, fname, fval)
    super(MyModel, self).save()

4👍

I get primary key’s name, use it to filter with Queryset.filter() and update with Queryset.update().

fooinstance = ...    
# Find primary key and make a dict for filter
pk_name foomodel._meta.pk.name
filtr = {pk_name: getattr(fooinstance, pk_name)}
# Create a dict attribute to update
updat = {'name': 'foo', 'lastname': 'bar'}
# Apply
foomodel.objects.filter(**filtr).update(**updat)

This allows me to update an instance whatever the primary key.

👤Zulu

4👍

Update using update()

Discussion.objects.filter(slug=d.slug)
    .update(title=form_data['title'],
            category=get_object_or_404(Category, pk=form_data['category']),
            description=form_data['description'], closed=True)

Leave a comment