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

前端 未结 5 1786
盖世英雄少女心
盖世英雄少女心 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:51

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

提交回复
热议问题