如何在Django中通过HttpResponse或JsonResponse发送多个对象

时间:2019-06-17 10:06:06

标签: django django-views httpresponse jsonresponse

我的视图函数中有两个对象influencer_data和user_list。我想通过HttpResponse方法发送influencer_data和user_list并获取Json格式的数据。

我的视图功能是:

def index(request):
    influencers = Influencer.objects.all()

    influencer_data = serializers.serialize("json",influencers) 
    user_list = UserList.objects.all()
    user_list = serializers.serialize("json",user_list)
    context = {
        'influencer_data':influencer_data,
        'user_list':user_list,

    }


    return HttpResponse(influencer_data,user_list, content_type='application/json')

当我同时通过influencer_data和user_list时,都会出现错误

__init__() got multiple values for argument 'content_type'

当我将return HttpResponse语句更改为

return HttpResponse(context, content_type='application/json')

我明白了

influencer_datauser_list

即只是字典中的键值
当我将return语句更改为

return HttpResponse(json.dumps(context), content_type='application/json')

我得到的输出为:

    "influencer_data": "[{\"model\": \"influencer_listings.influencer\", \"pk\": 8794, \"fields\": {\"full_name\": \"F A I Z S H A I K H \\ud83c\\udf08\", \"username\": \"mr_faizzz_07\", \"photo\": \"\", \"email_id\": \"\", \"external_url\": \"\", \"location_city\": \"Mumbai\", \"categories\": \"\", \"hashtags\": \"['#foryou', '#blessyou', '#all', '#faizanshaikh', '#keepsmiling', '#blessed', '#look', 

(Json对象变为字符串)
当我仅传递一个对象时,即impacter_data或user_list。我得到一个Json对象,即它可以正常工作(我想要给定格式的数据)

[
    {
        "model": "influencer_listings.influencer",
        "pk": 8794,
        "fields": {
            "full_name": "F A I Z S H A I K H ?",
            "username": "mr_faizzz_07",
            "photo": "",
            "email_id": "",
            "external_url": "",
            "location_city": "Mumbai",
            "categories": "",
            "hashtags": "['#foryou', '#blessyou', '#all', '#faizanshaikh', '#keepsmiling', '#blessed', '#look', '#ramzan', '#loveyou', '#lover', '#cuteboys', '#keepgoing', '#picoftheday', '#feathers', '#brothers', '#faizshaikhhhh', '#pictures', '#jummahmubarak', '#lovers']",

我应该如何处理?

1 个答案:

答案 0 :(得分:0)

def index(request):
    influencers = Influencer.objects.all().values()
    user_list = UserList.objects.all().values()
    context = {
        'influencer_data': influencer_data,
        'user_list': user_list,
    }
    data = json.dumps(context, indent=4, sort_keys=True, default=str)
    return HttpResponse(data, content_type='application/json')