同一文件中的Python和Django模型没有看到对方

class B(models.Model):
    whatever = models.TextField(blank=True)

    @staticmethod
    def are_we_ok():
        return False

class A(models.Model)
    text = models.TextField(blank=True)

    @staticmethod
    def is_everything_ok():
        if not B.are_we_ok():
            raise B.DoesNotExist




A.is_everything_ok()

为什么我收到错误

File "asdf/models.py",line x,in is_everything_ok
    if not B.are_we_ok():

AttributeError: 'nonetype' object has no attribute 'are_we_ok'

但是,如果我这样做:

class A(models.Model)
    text = models.TextField(blank=True)

    @staticmethod
    def is_everything_ok():
        from asdf.models import B
        if not B.are_we_ok():
            raise B.DoesNotExist

有用.这对我没有任何意义.这是巨大的Django应用程序的一部分.任何想法可能会导致什么样的情况? (例如,循环依赖可能吗?)

更新:

我忘了提到这个代码已经运行了四年没有任何麻烦.最近一些不相关的编辑引发了这个错误.

解决方法

用@classmethod替换@staticmethod.使用staticmethod时,self或类都不会作为第一个参数传递,这就是您无法调用方法的原因.

如果切换,则需要将该类添加函数的第一个参数:

class B(models.Model):
    whatever = models.TextField(blank=True)

    @classmethod
    def are_we_ok(cls):
        return False

有关更多信息,请参阅:What is the difference between @staticmethod and @classmethod in Python?.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...