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

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


当前回答

只是补充一下@Mallory-Erik说的话: 你可以把objects = models.Manager()放在情态句中:

class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    # ...
    def __str__(self):
        return self.question_text
    question_text = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    objects = models.Manager()

其他回答

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

如何抑制每行特定于每个错误的错误?

就像这样:https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

错误:类'class_name'没有'member_name'成员 它可以被抑制在这一行:

  # pylint: disable=no-member

这就是答案。 从我的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.

你可以为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]": {

    }
}