Search code examples
pythondjango-views

I'm new to Django, there is a warning but i can‘t solve it


warningpng

from django.shortcuts import render
from django.http import HttpResponse
from .models import ArticlePost
def article_list(request):
    articles = ArticlePost.objects.all()
    context = {'articles': articles}
    return render(request,'article/list.html',context)

# warning is:Class 'ArticlePost' is an unresolved feature reference for the 'objects'

besides, models.py and setting.py are followed: models.py](https://i.sstatic.net/UDrgP.png) [setting.py`

Looking forward to your help.

I ran python manage.py check ,terminal display "System check identified no issues (0 silenced)."


Solution

  • This is just PyCharm that does not undestand Django's metaprogramming logic. Indeed, Any subclass of a Model (that is not abstract) contains a manager named objects, if you don't specify a manager manually. But this is done through the ModelBase metaclass [GitHub]:

        def _prepare(cls):
            # …
            if not opts.managers:
                manager = Manager()
                manager.auto_created = True
                cls.add_to_class("objects", manager)

    But this is often a bit too much for a simple IDE, that thus fails to understand the metaprogramming, and therefore some IDEs and code validators will report a warning or error that the class has no attribute named .objects.

    There are linters like pylint-django [pypi.org] that include rule to reason about this. Additionally, PyCharm has a paid version that includes Django support that has added extra rules that allows the IDE to reason about Django models.