返回QuerySet的所有值并序列化为JSON

2024-04-20 12:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在这段代码中,所有的值都被指定为返回一个QuerySet

import json

posts = (Post.objects.filter(owner=authenticated_user)
                 .values('id', 'title', 'summary'))
json_posts = json.dumps(list(posts))

有没有办法避免为QuerySet('id'、'title'和'summary')指定所有值?例如

^{pr2}$

编辑:

最终的目标是将QuerySet序列化为JSON。以下代码引发AttributeError

try:
    obj = SystemOverview.objects.filter(serial=pk).values()
except SystemOverview.DoesNotExist:
    return Response(status=status.HTTP_404_NOT_FOUND)

if request.method == 'GET':
    return Response(serializers.serialize("json", list(obj)))

#ERROR MESSAGE
#AttributeError: 'dict' object has no attribute '_meta'

在不列出Django对象模型的所有值的情况下,将Django对象模型序列化为JSON的正确方法是什么?


Tags: 代码idjsonobj序列化objectstitlesummary
1条回答
网友
1楼 · 发布于 2024-04-20 12:23:34

如Django文档中所述https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values

The values() method takes optional positional arguments, *fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table.

只需使用Post.objects.filter(owner=authenticated_user).values()

编辑:

objs = SystemOverview.objects.filter(serial=pk).values()

if request.method == 'GET':
    return Response(serializers.serialize("json", objs))

相关问题 更多 >