Suppose I have a model like this:
class Book(models.Model):
num_pages = ...
author = ...
date = ...
Can I create a dictionary,
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()