我如何使用字典来更新Django模型中的字段?[英] How do I use a dictionary to update fields in Django models?

本文是小编为大家收集整理的关于我如何使用字典来更新Django模型中的字段?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

假设我有这样的模型:

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

我可以创建一个字典,然后使用它插入或更新模型?

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

推荐答案

以下是使用字典d:

创建的示例
Book.objects.create(**d)

要更新现有模型,您将需要使用QuerySet filter方法.假设您知道要更新的书的pk:

Book.objects.filter(pk=pk).update(**d)

其他推荐答案

使用**创建新模型.通过字典循环并使用setattr()以更新现有模型.

来自汤姆·克里斯蒂(Tom Christie)的django休息框架

django-rest-framework/blob/master/rest_framework/serializers.py

for attr, value in validated_data.items():
    setattr(instance, attr, value)
instance.save()

其他推荐答案

如果您知道要创建它:

Book.objects.create(**d)

假设您需要检查现有实例,则可以使用get或创建:

找到它:

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

正如另一个答案中提到的那样,您也可以在QuerySet Manager上使用update函数,但我相信这不会发送任何信号(如果您不使用它们对您来说可能无关紧要).但是,您可能不应该使用它来改变一个对象:

Book.objects.filter(id=id).update()

本文地址:https://www.itbaoku.cn/post/597483.html

问题描述

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"}

推荐答案

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)

其他推荐答案

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

其他推荐答案

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