首页 > 解决方案 > 在 Django Polls 教程中:获取“NameError: name 'Question' is not defined”

问题描述

已解决:我需要在 shell 中导入对象。

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

运行命令Question.objects.all()返回错误NameError: name 'Question' is not defined.

我的 polls/models.py 看起来像这样:


from django.db import models
from django.utils import timezone
import datetime

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

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

令人费解的是,我为本教程的第一个片段运行了 shell 并且没有任何问题。我能够创建一个 Question 对象并对其进行查询并完成所有预期的事情。我对 models.py 进行了一些编辑(添加了时区和str(因为已注释掉并在此处删除)),现在根本无法识别 Question 类。

这是怎么回事?

谢谢你的帮助。

标签: django-models

解决方案


from polls.models import Choice, Question # 导入我们刚刚写的模型类。


推荐阅读