【问题标题】:Django JSON Serialization with Mixed Django models and a Dictionary具有混合 Django 模型和字典的 Django JSON 序列化
【发布时间】:2010-12-29 21:13:40
【问题描述】:

我似乎找不到将 Django 模型和 Python 字典一起序列化的好方法,我通常会返回看起来像这样的 json 响应

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

使用 simplejson 序列化 dict 或 Django 的 serializers.serialize 序列化模型非常简单,但是当我将它们混合在一起时会出错。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python django json serialization


    【解决方案1】:

    我正在使用这个(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)
    

    使用此方法,您可以只选择您想要的字段(使 json 和数据库查询更小)。

    【讨论】:

      【解决方案2】:

      你不能把模型实例转换成字典,加入另一个字典然后序列化吗?

      from django.forms import model_to_dict
      
      dict = model_to_dict(instance)
      dict.update(dict2)
      
      ... Then serialize here ...
      

      不知道“更好”... :-)

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2011-02-21
      • 2011-09-04
      • 1970-01-01
      • 2016-08-23
      • 2020-04-28
      • 2011-01-16
      相关资源
      最近更新 更多