python - 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")
解决方案
您可以将两者都包装在字典中,例如:
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
.
推荐阅读
- java - jUnit 测试抛出 NullPointerException
- django - 为什么我会收到 pymongo ServerSelectionTimeoutError?
- python - 从 python 库调用用户定义函数有哪些好方法?
- flutter - Flutter 发行版 apk 显示黑屏或无法解析配置“:app:profileRuntimeClasspath”的所有工件
- pandas - 如何将 Pandas 数据框转换为模式中具有联合类型的 PyArrow 表?
- deep-learning - 批次数和历元
- reactjs - React 应用程序无法编译,似乎 typescript 没有被转译为 JS?
- javascript - Vue 测试 - '... .push 不是函数'
- scala - 根据RDD上的Userid计算用户评分平均值和映射
- html - 引导轮播卡从下到上定位