pythondatabasedjango

How do I use a dictionary to update fields in Django models?


Suppose I have a model like this:

class Book(models.Model):
    num_pages = ...
    author = ...
    date = ...

Can I create a dictionary, and then insert or update the model using it?

d = {"num_pages":40, author:"Jack", date:"3324"}

Solution

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