[Django]-Unresolved attribute reference 'objects' for class '' in PyCharm

181👍

You need to enable Django support. Go to

PyCharm -> Preferences -> Languages & Frameworks -> Django

and then check Enable Django Support

48👍

You can also expose the default model manager explicitly:

from django.db import models

class Foo(models.Model):
    name = models.CharField(max_length=50, primary_key=True)

    objects = models.Manager()

22👍

Use a Base model for all your models which exposes objects:

class BaseModel(models.Model):
    objects = models.Manager()
    class Meta:
        abstract = True


class Model1(BaseModel):
    id = models.AutoField(primary_key=True)

class Model2(BaseModel):
    id = models.AutoField(primary_key=True)

6👍

You can try install django-stubs

pip install django-stubs

4👍

In pycharm professional you can do that:

PyCharm -> Preferences -> Languages & Frameworks -> Django

and then check Enable Django Support

If you are using pycharm community you can do it;

add models.Manager() at your objects model propery

class MyModel(models.Model):
    objects = models.Manager()

additionally you can use pip install django-stubs

3👍

Python Frameworks (Django, Flask, etc.) are only supported in the Professional Edition.
Check the link below for more details.

PyCharm Editions Comparison

2👍

I found this hacky workaround using stub files:

models.py

from django.db import models


class Model(models.Model):
    class Meta:
        abstract = True

class SomeModel(Model):
    pass

models.pyi

from django.db import models

class Model:
    objects: models.Manager()

This should enable PyCharm’s code completion:
enter image description here

This is similar to Campi’s solution, but avoids the need to redeclare the default value

0👍

Another solution i found is putting @python_2_unicode_compatible decorator on any model.
It also requires you to have a str implementation four your function

For example:

# models.py

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class SomeModel(models.Model):
    name = Models.CharField(max_length=255)

    def __str__(self):
         return self.name

0👍

If you are using PyCharm Community, you can ignore it in your settings: go to "Settings/Editor/Inpections/Unresolved references"

And then in "Options/Ignored references" add this line, replacing the name of your project. This will get rid of this warning. Ignoring this has had no negative effects for me.

<name of your project>.models.*

Leave a comment