【问题标题】:TypeError 'tuple' object is not callableTypeError 'tuple' 对象不可调用
【发布时间】:2017-02-09 13:05:54
【问题描述】:

我遇到了一个错误, /ResultJSON/v1/results/ 处的类型错误 'tuple' 对象不可调用。

我在views.py中写了一个方法,

results = OrderedDict([
        ('id',x.id)
        ('name', x.name)
        for x in Post.objects.all()
    ])

当我浏览这个错误时,我读到这个错误是因为没有逗号(,)。

但是我在 ('id',x.id) 和 ('name', x.name) 和最后一个 ('name', x.name) 之间添加了逗号,我得到一个错误没有为项目。

所以,我不明白为什么会发生这个错误。我该如何解决?

在views.py中,我写了

import json
from collections import OrderedDict
from django.http import HttpResponse
from accounts.models import Post


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 = OrderedDict([
        ('id',x.id)
        ('name', x.name)
        for x in Post.objects.all()
    ])

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

【问题讨论】:

  • 你想在这里实现什么?字典只能保存 唯一 键,您不能生成多个 idname 键并使其正常工作。
  • 您是否正在尝试生成一个字典列表

标签: python django


【解决方案1】:

您正在混合语法;您不能将列表推导式与一些文字元素混合在一起,并且列表推导式每次迭代不能产生多个元素。

此外,您不能生成包含多个键副本的字典(有序或其他)。

我怀疑您试图在一个列表中创建多个字典,每个字典都包含 id 和 name:

results = [OrderedDict([('id', x.id), ('name', x.name)])
           for x in Post.objects.all()]

只查询数据库的id和name字段可能更高效、更易读:

fields = ('id', 'name')
results = [OrderedDict(zip(fields, x))
           for x in Post.objects.order_by. values_list(*fields)]

【讨论】:

    【解决方案2】:

    您尝试做的整个有序 dict 看起来有点不必要,只需使用 django 查询集创建它

    results = Post.objects.order_by().values_list('id', 'name')  # or values()..
    

    【讨论】:

    • 使用values()(返回字典)而不是values_list(返回元组)会更加一致。上述方法将起作用,除非响应中键的顺序很重要,在这种情况下,需要一个有序的字典。
    • @Alasdair - 是的,我还没有弄清楚哪个最适合 OP 的用例,因为它根本不清楚他们打算在什么上使用它。 (我想不出任何有序 dicts 列表有用的地方..)
    • 谢谢,你的 cmets。当我写你的代码时,我得到一个错误,TypeError at /ResultJSON/v1/results/ is not JSON serializable 我能做些什么来解决它?
    • @user7523656 - 你可以回复Martijn Pieter's comment...
    猜你喜欢
    • 2021-10-14
    • 2013-08-27
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2021-04-15
    • 2011-10-01
    • 2020-11-10
    相关资源
    最近更新 更多