Django/Visual Studio Tutorial - objects method err

2020-07-16 12:09发布

问题:

I'm working through the Django Tutorial (here). I'm using visual studio on a Mac and VS keeps showing an error on this code:

latest_question_list = Question.objects.order_by('-pub_date')[:5]

The error reads Class 'Question' has no 'objects' member.

The example builds a Questions Class which in fact doesn't directly have an objects member, but the code runs fine and I think that there is a built in member within Django that has objects.

So that leads me to believe that the visual studio debugger is raising an error that doesn't actually exist.

Is there a way to fix this?

I've looked through preferences/setting and under extensions to see if there is a plugin or setting reference that could be made to Django to clear the error within Visual Studio - I didn't see anything.

回答1:

That is not error, just a warning from the Visual Studio Code. objects is a Manager instance which is added to our model classes dynamically by django. When VS Code checks the class declaration, it do not found objects declaration there, so warns us about a possible error.

In, Visual Studio code, python extension uses pylint as default linter.

To work it properly you can install pylint locally as:

pip install pylint

Or, you can also disable linting by configuring the following property in either one of (User or Workspace settings file) as follows:

"python.linting.enabled": false

For django projects, you can customize the pylint plugin by modifying the User or Workspace settings as follows:

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


回答2:

For anyone who gets "Expected comma" error in User Settings, put comma to previous argument and after this one "python.linting.pylintArgs": ["--load-plugins", "pylint_django"]

Must be like this:

{
    "python.pythonPath": "C:\\Program Files (x86)\\Python37-32\\python.exe",
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
    "[python]": {

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