Django JSON串行化与混合Django模型和词典 [英] Django JSON Serialization with Mixed Django models and a Dictionary

查看:122
本文介绍了Django JSON串行化与混合Django模型和词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到一个将Django模型和Python字典序列化在一起的好方法,对我来说,很常见的是返回类似于

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

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

它足够简单,可以使用simplejson来序列化一个dict或Django的serializers.serialize来序列化一个模型,但是当我混合在一起我得到错误。

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.

有更好的方法吗?

推荐答案

可以你只是将模型实例转换成一个dict,加入另一个dict,然后序列化?

Can't you just convert the model instance to a dict, join the other dict and then serialize?

from django.forms import model_to_dict

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

... Then serialize here ...

不知道是否更好...: - )

Don't know about being "better"... :-)

这篇关于Django JSON串行化与混合Django模型和词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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