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

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

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

提交回复
热议问题