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)
- [Django]-Django templates: verbose version of a choice
- [Django]-IntegrityError duplicate key value violates unique constraint – django/postgres
- [Django]-Django: Does prefetch_related() follow reverse relationship lookup?
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()
- [Django]-How to assign items inside a Model object with Django?
- [Django]-Override default queryset in Django admin
- [Django]-Get object by field other than primary key
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
- [Django]-Django DB Settings 'Improperly Configured' Error
- [Django]-How does one make logging color in Django/Google App Engine?
- [Django]-Django 1.10.1 'my_templatetag' is not a registered tag library. Must be one of:
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)
- [Django]-Itertools.groupby in a django template
- [Django]-How to get the username of the logged-in user in Django?
- [Django]-Unittest Django: Mock external API, what is proper way?
Source:stackexchange.com