首页 > 解决方案 > Django:返回查询集和字符串

问题描述

在 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")

标签: pythonjsondjangodjango-viewshttpresponse

解决方案


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

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': jloads(serialize('json', objs)),
    'text': text
}

return JsonResponse(allData)

因此,数据是一个带有两个键的 JSON 对象:objs将包含序列化的查询集,text并将包含text.


推荐阅读