【问题标题】:django 'str' object has no attribute '_meta'django 'str' 对象没有属性 '_meta'
【发布时间】:2017-10-31 09:29:50
【问题描述】:

对不起我的英语。我有一些来自另一台服务器的数据,但我需要像 JSON 一样输出这些数据。

如果我在控制台中打印响应

{
    'responseStatus': {
        'status': [],
    },
    'modelYear': [
        1981,
        1982

    ]
}

但是,如果我像HttpResponse 这样返回这个响应,我有错误

AttributeError: 'str' 对象没有属性 '_meta'

这是我的代码:

data = serializers.serialize('json', response, ensure_ascii=False)
return HttpResponse(data, content_type="application/json")

UPD:

我确实喜欢这个

from django.http import JsonResponse

def some_view(request):
    ...
    return JsonResponse(response, safe=False)

但有错误:

“ModelYears”类型的对象不是 JSON 可序列化的

UPD:

我喜欢这个

import json
from django.http import JsonResponse

def some_view(request):
        ...
        return JsonResponse(json.loads(response))

但有错误

the JSON object must be str, bytes or bytearray, not 'ModelYears'

【问题讨论】:

    标签: python json django


    【解决方案1】:

    Django docsserializers 框架的描述如下:

    Django 的序列化框架提供了一种将 Django 模型“转换”为其他格式的机制。

    错误表明您的变量 responsestring 而不是 Django 模型对象。该字符串似乎是有效的JSON,因此您可以使用JsonResponse

    import json
    from django.http import JsonResponse
    
    # View
    return JsonResponse(json.loads(response))
    

    【讨论】:

    • 感谢您的回答。我确实像你说的那样,但我有错误the JSON object must be str, bytes or bytearray, not 'ModelYears'我更新了问题
    • 假设类型是string 似乎我错了。你是如何创建response 变量的?
    • 我使用 zeep 库进行 xml 请求。我的response 我这样创建response = client.service.getModelYears(accountInfo=account_info)
    • 我明白了,遗憾的是我没有使用该库的经验,所以我不知道您的 response 变量的类型。也许您可以在文档中的某个地方找到它,看看是否有办法从那里转到JSON
    【解决方案2】:

    用以下代码替换您的代码:

    from django.http import JsonResponse
    
    def some_view(request):
        ...
        return JsonResponse(response)
    

    而不是通过httpresponse序列化和发送。

    【讨论】:

    • 感谢您的评论,我确实像您说的但有错误Object of type 'ModelYears' is not JSON serializable我更新问题
    【解决方案3】:

    这适用于 python 3.6 和 Django 2.0

    from django.contrib.auth.decorators import login_required
    from django.http import HttpResponse, JsonResponse
    import requests
    
    @login_required()
    def get_some_items(request):
        headers = {"Authorization": "Token uydsajbkdn3kh2gj32k432hjgv4h32bhmf"}
        host = "https://site/api/items"
    
        response = requests.get(host, headers=headers)
        result = JsonResponse(response.json())
    
        return HttpResponse(result, content_type='application/json')
    

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2022-09-23
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多