简体   繁体   English

如何从静态方法访问Django模型的反向外键?

[英]How can I access a Django model's reverse foreign key from a staticmethod?

Suppose I have 3 Django models: 假设我有3个Django模型:

class MyModelA(models.Model):
    my_int = models.IntegerField()

    @staticmethod
    def my_Astatic_method():
        return "AHello"

class MyModelB(models.Model):
    my_int = models.IntegerField()
    my_a = models.ForeignKey(MyModelA, related_name="MyModelB_a")


    @staticmethod
    def my_Bstatic_method():
        return "BHello"

class MyModelC(models.Model):
    my_int = models.IntegerField()
    my_b = models.ForeignKey(MyModelB, related_name="MyModelC_b")

    @staticmethod
    def my_Cstatic_method():
        return "CHello"

I have an instance of MyModelA called a . 我有一个实例MyModelA称为a From within a method of a , I would like to call my_Cstatic_method() . 从方法中a ,我想打电话给my_Cstatic_method() How can I do it? 我该怎么做?

a.MyModelB_a.model.my_Bstatic_method() works to call MyModelB 's static method. a.MyModelB_a.model.my_Bstatic_method()可以调用MyModelB的静态方法。 But I don't know how to get one level down into MyModelC 's static methods from MyModelB 's model attribute. 但是我不知道如何从MyModelBmodel属性中深入MyModelC的静态方法。 How should I do it? 我该怎么办?

Surprisingly, there is no model attribute for the object a.MyModelB_a.model.MyModelC_b 令人惊讶的是,对象a.MyModelB_a.model.MyModelC_b没有model属性

After accessing model B from model A, you don't have model instance anymore, but model class. 从模型A访问模型B后,您不再具有模型实例,而是模型类。

With class, there is no fields but rather field descriptors, also for related fields, so there shoudl be MyModelC_b here: 对于类,没有字段,只有字段描述符,也有相关字段的描述符,因此这里应该是MyModelC_b

a.MyModelB_a.model.MyModelC_b

but, as I said this isn't a field, but it have reference to related model as an sub-attribute in attribute related : 但是,正如我所说,这是不是一个领域,但它具有一定的参考相关模型作为子属性在属性related

a.MyModelB_a.model.MyModelC_b.related.model

using that, you can now accss your static function from model C 使用它,您现在可以从模型C访问您的静态函数

a.MyModelB_a.model.MyModelC_b.related.model.my_Cstatic_method()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM