【问题标题】:Django: Return queryset and stringDjango:返回查询集和字符串
【发布时间】:2021-02-19 22:24:40
【问题描述】:

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

【问题讨论】:

    标签: python json django django-views httpresponse


    【解决方案1】:

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

    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 中的值。

    【讨论】:

    • 哇即时回复:-) 感谢添加逗号后完美工作:allData = { 'objs': jloads(serialize('json', objs)), 'text': text }
    猜你喜欢
    • 2016-07-21
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多