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中运行了这个命令,但是什么都没有。

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


当前回答

当我使用pylint_runner时发生了这个问题

我要做的是打开。pylintrc文件并添加这个

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=objects

其他回答

我安装了PyLint,但我有错误Missing module docstringpylint(Missing -module-docstring)。所以我用pylint的配置找到了这个答案:

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
    "--disable=C0111", // missing docstring
    "--load-plugins=pylint_django,pylint_celery",
 ],

现在起作用了

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

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

Python:选择Linter

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

安装Django pylint:

pip install pylint-django

ctrl+shift+p >首选项:配置语言特定设置> Python

设置。适用于python语言的Json应该如下所示:

{
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django"
    ],

    "[python]": {

    }
}

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

这就是答案。 从我的reddit帖子… https://www.reddit.com/r/django/comments/6nq0bq/class_question_has_no_objects_member/

That's not an error, it's just a warning from VSC. Django adds that property dynamically to all model classes (it uses a lot of magic under the hood), so the IDE doesn't know about it by looking at the class declaration, so it warns you about a possible error (it's not). objects is in fact a Manager instance that helps with querying the DB. If you really want to get rid of that warning you could go to all your models and add objects = models.Manager() Now, VSC will see the objects declared and will not complain about it again.