简体   繁体   中英

How to call a static method from a Django model “backward link”?

These are my two Django Models, MyModelB has a foreign key to MyModelA :

from django.db import models


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

    def __str__(self):
        return "MyModelA #%s: my_int=%s" % (
            self.pk,
            self.my_int,
        )

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

    def __str__(self):
        return "MyModelB #%s: my_int=%s" % (
            self.pk,
            self.my_int,
        )

    @staticmethod
    def my_static_method():
        return "Hello"

I create an instance of MyModelA and MyModelB :

>>> a = MyModelA(my_int=20)
>>> a.save()
>>> a
<MyModelA: MyModelA #3: my_int=20>

>>> b = MyModelB(my_int=30, my_a=a)
>>> b.save()
>>> b
<MyModelB: MyModelB #3: my_int=30>

From the instance of MyModelA , I can reference the MyModelB using "reverse-links":

>>> a.MyModelB_a.filter(my_int=30)
[<MyModelB: MyModelB #3: my_int=30>]

But I want to call MyModelB.my_static_method() from the instance of MyModelA . How can I do it? My attempted solution doesn't work:

>>> a.MyModelB_a.my_static_method()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'RelatedManager' object has no attribute 'my_static_method'
>>>

You'll have to access the model class in order to call the static method.

Use a.MyModelB_a.model.my_static_method()

The model attribute returns the model class MyModelB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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