0

Suppose I have 2 Django applications in my project: appA, appB.

appA contains ModelA as follows in its models.py:

class ModelA(models.Model):
    field1 = models.CharField(max_length=254, null=False, blank=False,)

appB contains ModelB as follows in its modesl.py:

from appA.models import modelA

class ModelB(models.Model):
    field2 = models.CharField(max_length=254, null=False, blank=False,)
    model_A = models.ForeignKey(ModelA, related_name="blahblah")

Now I would like to add an @property function to ModelA that will return all instances of ModelB that have this ModelA as their foreign key:

@property
def matching_model_bs(self):
    return ModelB.objects.filter(model_A=self)

But to do this, I have to import appB.models into appA.models, but that would cause a circular import. So how can I achieve this without running into circular imports?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

4

There's no need for that property. The functionality is already built in: you can just do mymodelA.modelb_set.all().

(Actually, since you've set related_name here, it would be mymodelA.blahblah.all().)

See the docs on following relations backward.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895