【问题标题】:TypeError: argument of type 'function' is not iterable : django errorTypeError:“函数”类型的参数不可迭代:django 错误
【发布时间】:2020-03-14 12:35:18
【问题描述】:

我正在为投票应用创建 API,但遇到了这个错误

error.TypeError:“函数”类型的参数不可迭代:django 错误我的模型:

我该如何处理?代码中似乎没有错误。

代码:

from django.db import models
from django.contrib.auth.models import User


class Poll(models.Model):
    question = models.CharField(max_length=100)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    pub_date = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.question


class Choice(models.Model):
    poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=100)

def __str__(self):
    return self.choice_text


class Vote(models.Model):
    choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE)
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
    voted_by = models.ForeignKey(User, on_delete=models.CASCADE)

class Meta:
    unique_together = ("poll", "voted_by")

我的看法:

from django.shortcuts import render, get_object_or_404
    from django.http import JsonResponse

from .models import Poll

def polls_list(request):
    MAX_OBJECTS = 20
    polls = Poll.objects.all()[:MAX_OBJECTS]
    data = {"results": list(polls.values("question", "created_by__username", "pub_date"))}
    return JsonResponse(data)


def polls_detail(request, pk):
    poll = get_object_or_404(Poll, pk=pk)
    data = {"results": {
        "question": poll.question,
        "created_by": poll.created_by.username,
        "pub_date": poll.pub_date
     }}
   return JsonResponse(data)

【问题讨论】:

  • 显示回溯,以便我们查看错误发生的位置。

标签: python django function typeerror


【解决方案1】:

试试这个,因为我不确定切片的效果如何:


def polls_list(request):
    MAX_OBJECTS = 20
    polls = Poll.objects.values("question", "created_by__username", "pub_date")
    data = {"results": list(polls[:MAX_OBJECTS])}
    return JsonResponse(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2019-10-18
    • 2021-10-28
    • 1970-01-01
    • 2020-09-07
    • 2020-06-28
    • 2021-01-15
    相关资源
    最近更新 更多