微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

同一文件中的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?.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐