def index(request):
   latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
   template = loader.get_template('polls/index.html')
   context = {'latest_question_list':latest_question_list}
   return HttpResponse(template.render(context, request))

该函数的第一行在Question.objects.all()上得到一个错误:

类“Question”没有“objects”成员

我正在跟随Django文档教程,它们有相同的代码并正在运行。

我已经尝试调用一个实例。

Question = new Question()
and using MyModel.objects.all()

这个类的models。py代码是这样的。

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

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    def __str__(self):
        return self.question_text

我仍然有这个错误。

我读过pylint并运行了这个…

pylint --load-plugins pylint_django

这并没有帮助,即使github自述文件说…

防止关于django生成的属性的警告 模型。objects或Views.request。

我在virtualenv中运行了这个命令,但是什么都没有。

所以任何帮助都是最好的。


当前回答

只需在你的问题表中添加objects = None。这为我解决了错误。

其他回答

把你的绒线改为- flake8,问题就会消失。

如果你使用python 3

python3 -m pip install pylint-django

如果python < 3

python -m pip install pylint-django==0.11.1

注意:版本2.0,需要pylint >= 2.0,不再支持Python 2 !(https://pypi.org/project/pylint-django/)

你可以为Visual Studio Code更改Python扩展的linter。

在VS中打开命令面板Ctrl+Shift+P,输入以下命令之一:

Python:选择Linter

当你选择一个linter,它将被安装。我试过flake8,似乎问题解决了。

我已经尝试了所有可能的解决方案,但不幸的是,我的vscode设置不会改变它的linter路径。所以,我尝试在settings > User settings > python中探索vscode设置。找到Linting: Pylint Path并将其更改为“pylint_django”。不要忘记在>用户设置> python配置中将linter从“pyLint”改为“pylint_django”。

通过执行Question = new Question()(我假设new是一个拼写错误),您正在用一个Question实例覆盖Question模型。就像Sayse在评论中说的:不要使用与模型名称相同的变量名。因此,将其更改为my_question = Question()。