【问题标题】:AttributeError 'list' object has no attribute 'id'AttributeError 'list' 对象没有属性 'id'
【发布时间】:2017-02-08 13:49:11
【问题描述】:

我遇到了一个错误, /ResultJSON/v1/results/ 处的 AttributeError 'list' 对象没有属性 'id' 。

在 ResultJSON(child app) 的 views.py 中,我写了

import json
from collections import OrderedDict
from django.http import HttpResponse

def render_json_response(request, data, status=None):

    json_str = json.dumps(data, ensure_ascii=False, indent=2)
    callback = request.GET.get('callback')
    if not callback:
        callback = request.POST.get('callback')
    if callback:
        json_str = "%s(%s)" % (callback, json_str)
        response = HttpResponse(json_str, content_type='application/javascript; charset=UTF-8', status=status)
    else:
        response = HttpResponse(json_str, content_type='application/json; charset=UTF-8', status=status)
    return response

def UserResult(request):
    results = []
    results = OrderedDict([
    ('id',results.id),
    ('name', results.name),
    ])
    results.append(results)

    data = OrderedDict([ ('results', results) ])
    return render_json_response(request, data)

我真的不明白为什么会发生这个错误,因为我的数据库(sqlite)有 id 列。

我想让系统从数据库中获取数据(id&name 是列的名称,这些数据在我的数据库中)并将这些数据编码为 JSON。

那么,我该如何解决这个问题?我认为也许 models.py 是错误的......(因为子应用的 models.py 没有代码。)

【问题讨论】:

  • results = [] 后跟foo = ... results.id ... 看起来很可疑!

标签: python django


【解决方案1】:

您的results 变量是一个python 列表,您看到的错误是正常的,因为该列表没有名为id 的属性

我认为您想要实现的目标如下:

def UserResult(request):
    results = OrderedDict([
        ('id', x.id), ('name', x.name)
        for x in YourChildModel.objects.all()
    ])

    data = OrderedDict([ ('results', results) ])
    return render_json_response(request, data)

最好关注pep8 naming convention,因为您正在使用 Python 进行编码,以便其他人可以轻松理解您在做什么。

【讨论】:

  • thx, ur cmets.I didn't know Django's JsonResponse ,thx!!但我不明白你写的,你不必处理内容类型和json转储,所以它是什么意思render_json_response 方法没用?我应该在哪里添加这些代码?你会添加你的意思的示例代码吗?
  • 算了吧,在你试图附加回调的情况下,它不是很有用,只有当你有一个你想要返回的普通 python 对象时。让我知道您的问题是否已解决
猜你喜欢
  • 2023-04-09
  • 2014-09-08
  • 2016-01-30
  • 2020-12-15
  • 2016-04-15
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多