How do I use a dictionary to update fields in Django models?
Solution 1:
Here's an example of create using your dictionary d:
Book.objects.create(**d)
To update an existing model, you will need to use the QuerySet filter
method. Assuming you know the pk
of the Book you want to update:
Book.objects.filter(pk=pk).update(**d)
Solution 2:
Use **
for creating a new model. Loop through the dictionary and use setattr()
in order to update an existing model.
From Tom Christie's Django Rest Framework
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
Solution 3:
If you know you would like to create it:
Book.objects.create(**d)
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=d)
if not created:
for attr, value in d.items():
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()