我正在为民意调查应用程序创建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)
答案 0 :(得分:0)
请尝试尝试此操作,因为我不确定切片的效果如何:
4