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

前端 未结 5 1799
盖世英雄少女心
盖世英雄少女心 2020-12-23 02:21

Suppose I have a model like this:

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

Can I create a dictionary,

5条回答
  •  臣服心动
    2020-12-23 02:49

    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)
    

提交回复
热议问题