首页 > 解决方案 > '问题'对象没有属性'choice_set'django

问题描述

我尝试了 django polls 应用程序但得到了这个,我的模型包含外键但我不明白问题出在哪里

from django.db import models

class Question(models.Model):
    question = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('published date')

    def __str__(self):
        return self.question

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    vote = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

这是视图:

def vote(request , primary_key):
question = get_object_or_404(models.Question, id=primary_key)
try:
    selected_choice = question.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    return render(request,'polls/detail.html',{
        'question' : question ,
        'error_message' : "u didn't select a choice."
    })
else:
    selected_choice.vote += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('polls:results', args = (question.id)))

网址:

urlpatterns = [
re_path(r'^$', views.index , name = 'index'),
re_path(r'^(?P<primary_key>[0-9]+)/$',views.detail, name = 'detail'),
re_path(r'^(?P<primary_key>[0-9]+)/results/$' , views.results , name = 'results'),
re_path(r'^(?P<primary_key>[0-9]+)/vote/$' , views.vote , name = 'vote'),

]

标签: djangopython-3.xdjango-modelsdjango-views

解决方案


您是否在定义您的 Choice 类后进行了迁移并迁移了它们?


推荐阅读