Django模型与字典混合的JSON序列化

4 投票
2 回答
2723 浏览
提问于 2025-04-15 17:21

我找不到一个好的方法来把Django模型和Python字典一起转换成可以用的格式。通常我需要返回一个看起来像这样的json响应:

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

用simplejson来转换字典或者用Django的serializers.serialize来转换模型都很简单,但当我把它们混在一起的时候就会出错。

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

2 个回答

2

我正在使用这个(这里的 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和数据库查询变得更小)。

10

你难道不能把模型实例转换成一个字典,然后把其他的字典合并在一起,再进行序列化吗?

from django.forms import model_to_dict

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

... Then serialize here ...

我不知道这样做是否“更好”... :-)

撰写回答