django - '问题'对象没有属性'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'),
]
解决方案
您是否在定义您的 Choice 类后进行了迁移并迁移了它们?
推荐阅读
- java - 使用 JAVA 的正则表达式问题
- r - 如何使用 vfold_cv 获得欧洲防风多项逻辑回归模型的系数?
- awk - awk 将特定列从 file1 更新到 file2。但包括来自 file1 的其他记录
- python - 高阶函数和帧堆叠
- angular - PrimeNG - 面包屑 - 如何通过服务从子组件更新父组件中的 MenuItem 列表?
- javascript - react-native 中的“无法读取“未定义”的属性 createElement”错误
- c# - Raspberry Pi 3A+ 使用 Mono C# 来控制 SPI 连接
- python - 如何在 Django 中延长月份
- string - 键入'_InternalLinkedHashMap
' 不是类型 'String' 错误的子类型 - python - 如何检查像素的 hsv 是否在颜色的上下边界之间?