Django: How can I get the foreign key's class from a classmethod in the referred-to class?
<p>I have the following two Django Classes <code>MyClassA</code> and <code>MyClassB</code> in two separate files. <code>MyClassB</code> has a foreign key reference to an instance of <code>MyClassA</code>. <code>MyClassA</code> cannot import the class <code>MyClassB</code>.</p>

<p>my_class_a/models.py:</p>

<pre><code>from django.db import models
class MyClassA(models.Model):
    name = models.CharField(max_length=50, null=False)

    @classmethod
    def my_method_a(cls):
        # What do I put here to call MyClassB.my_method_b()??
</code></pre>

<p>my_class_b/models.py:</p>

<pre><code>from my_class_a.models import MyClassA   
from django.db import models

class MyClassB(models.Model):
    name = models.CharField(max_length=50, null=False)
    my_class_a = models.ForeignKey(MyClassA, related_name="MyClassB_my_class_a")

    @staticmethod
    def my_method_b():
        return "Hello"
</code></pre>

<p>From within <code>MyClassA</code>'s class method <code>my_method_a</code>, I would like to call <code>MyClassB</code>'s static method <code>my_method_b</code>. How can I do it? </p>

<p>If <code>my_method_a</code> was an instance method, I would simply do <code>self.MyClassB_my_class_a.model.my_method_b()</code>. But since I don't have an instance of <code>MyClassA</code>, I don't know how to do it. I would like to take advantage of the related_name field that allows for reverse lookups of instances.</p>

<p>You can do it like this.</p>

<pre><code>@classmethod
def my_method_a(cls):
    from myclass_b.models import MyClassB 
    # yes, you can have an import here. and it will not
    # lead to a cyclic import error
    MyClassB.my_method_b()
</code></pre>

<p>The import failure happens only if you add the import to the top of the file. That would lead to cyclic imports one module cannot be loaded because it depends on another which depends on the other module. However when the import is inside a method the same problem does not arise.</p>

python django foreign-keys static-methods class-method