【发布时间】:2017-02-07 15:27:31
【问题描述】:
我有 postgresql(和 postgis)的空间查询。我使用 raw() 函数。所以我有这样的事情:
observations = Square.objects.raw('SELECT validation_birds_square.id AS id,
validation_birds_square.identification,
Count(validation_birds_checklist.position) AS total
FROM validation_birds_square ...the rest of sql query...')
我使用我在 models.py 中定义的 Square 模型。然后我想序列化观察,所以我这样做:
return HttpResponse(serializers.serialize("json", observations), content_type='application/json')
但这就是问题所在。它仅序列化 Square 模型的属性,而不是来自 sql 查询的 total。
当我对观察结果进行迭代时,我可以获得该值:
for observation in observations:
print(observation.total)
有没有更好的方法将 total 放入序列化的 JSON,而不是迭代观察结果并将其手动序列化为 JSON?
【问题讨论】:
标签: json django serialization django-models