Django:Return 查询集和字符串

Django: Return queryset and string

在 Django 中,是否可以创建一个由查询集和文本字符串组合而成的 HttpResponse?

我想象的是这样的

objs = ModelName.objects.all()

text = "Some text"

allData = ??? #Some kind of operation (json.dumps, serializers, or ...) that combines the two

return HttpResonse(allData,content_type="application/json")

您可以将两者都包装在字典中,例如:

from django.http import JsonResponse
from django.core.serializers import serialize
from json import loads as jloads

objs = ModelName.objects.all()
text = 'Some text'

allData = {
    'objs': <b>jloads(</b>serialize('json', objs)<b>)</b>,
    'text': text
}

return JsonResponse(allData)

数据因此是具有两个键的 JSON 对象:objs 将包含序列化查询集,text 将包含 text 中的值。