简体   繁体   English

使用混合Django模型和字典的Django JSON序列化

[英]Django JSON Serialization with Mixed Django models and a Dictionary

I can't seem to find a good way to serialize both Django Models and Python dictionaries together, its pretty common for me to return a json response that looks like 我似乎无法找到一个很好的方法来同时序列化Django模型和Python字典,我常常返回一个看起来像json的响应

{
  "modified":updated_object,
  "success":true
  ... some additional data...
}

Its simple enough to use either simplejson to serialize a dict or Django's serializers.serialize to serialize a model but when I mix them together I get errors. 它很简单,可以使用simplejson序列化dict或Django的serializers.serialize来序列化模型,但是当我将它们混合在一起时,我会得到错误。

Is there a better way to do this? 有一个更好的方法吗?

Can't you just convert the model instance to a dict, join the other dict and then serialize? 你不能只是将模型实例转换为dict,加入另一个dict然后序列化吗?

from django.forms import model_to_dict

dict = model_to_dict(instance)
dict.update(dict2)

... Then serialize here ...

Don't know about being "better"... :-) 不知道“更好”...... :-)

I'm using this (where products is queryset): 我正在使用它( products是查询集):

response = {}
products_list = list(products.values('id', 'name', 'description'))
response['products'] = products_list
response['more_data'] = 'more, more, more, things'

json_data = json.dumps(response)

Using this method you can select only fields you want (make json, and database query smaller). 使用此方法,您只能选择所需的字段(使json和数据库查询更小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM