【问题标题】:How serialize count() from sql query to JSON如何将 sql 查询中的 count() 序列化为 JSON
【发布时间】: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


    【解决方案1】:

    您没有正确的查询集,因此使用内置序列化程序没有多大意义。只需创建一个字典列表,然后使用 JsonResponse 将其作为 JSON 返回。

    data = [{'id': o.id, 'identification': o.identification, 'total': o.total} for o in observations]
    return JsonResponse(data)
    

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 2022-01-18
      • 2016-06-27
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多