且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中将JSON转换为模型实例

更新时间:2023-12-02 13:55:16

***的方法是利用现有的Django应用程序,它们支持将模型实例与JSON进行序列化.

The best approach would be to utilize one of the existing Django applications that support serializing model instances to and from JSON.

无论哪种情况,如果您将JSON对象解析为Python字典,则基本上可以使用 QuerySet.update() 直接方法.

In either case, if you parse the JSON object to a Python dictionary, you can basically use the QuerySet.update() method directly.

因此,假设您得到一个字典,其中所有键都映射到模型属性,并且它们代表您想要更新的值,您可以这样做:

So, say you get a dictionary where all the keys map to model attributes and they represent the values you'd want to update, you could do this:

updates = {                                    # Our parsed JSON data
    'pk': 1337,
    'foo': 'bar', 
    'baz': 192.05
}

id = updates.pop('pk')                         # Extract the instance's ID
Foo.objects.filter(id=id).update(**updates)    # Update the instance's data