Saqib Ali Saqib Ali - 2 months ago 7
Python Question

Django: How can I get the foreign key's class from a classmethod in the referred-to class?

I have the following two Django Classes

MyClassA
and
MyClassB
in two separate files.
MyClassB
has a foreign key reference to an instance of
MyClassA
.
MyClassA
cannot import the class
MyClassB
.

my_class_a/models.py:

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()??


my_class_b/models.py:

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"


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

If
my_method_a
was an instance method, I would simply do
self.MyClassB_my_class_a.model.my_method_b()
. But since I don't have an instance of
MyClassA
, 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.

Answer

You can do it like this.

@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()

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.

Comments