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

查看:269
本文介绍了如何使用字典更新Django模型中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的模型:

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


推荐答案

使用您的字典d创建示例:

Here's an example of create using your dictionary d:

Book.objects.create(**d)

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

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)

这篇关于如何使用字典更新Django模型中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆