PyCharm中类''的未解析属性引用'对象'

问题描述 投票:32回答:5

我使用社区pycharm,python的版本是3.6.1,django是1.11.1。此警告对运行没有影响,但我无法使用IDE的自动完成。

python django pycharm
5个回答
65
投票

您需要启用Django支持。去

PyCharm - >首选项 - >语言和框架 - > Django

然后检查Enable Django Support


8
投票

您还可以显式公开默认模型管理器:

from django.models import models

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

    objects = models.Manager()

3
投票

Python Frameworks(Django,Flask等)仅在Professional Edition中受支持。请查看以下链接了解更多详情。

PyCharm Editions Comparison


1
投票

我找到的另一个解决方案是在任何模型上放置@ python_2_unicode_compatible装饰器。它还要求你有一个str实现四个函数

例如:

# 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
投票

我发现这个使用存根文件的hacky变通方法:

models.朋友

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()

这应该使PyCharm的代码完成:enter image description here

这类似于Campi的解决方案,但是无需重新声明默认值


0
投票

对所有暴露对象的模型使用Base模型:

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


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

class Model2(BaseModel):
    id = models.AutoField(primary_key=True)
© www.soinside.com 2019 - 2024. All rights reserved.