Search code examples
djangodjango-modelscircular-dependencyproject-structure

Importing models to encapsulate queries in properties is causing circular import issues


My problem is the following: For a while now I got used to encapsulate a few (the most relevant and reusable) queries of my application in properties within my Django models.

to do that, I constantly do:

from my_app.models import ModelBla

.....

class ModelBlehhh():
    @property
    def some_bla_things(self, bla):
        return ModelBla.objects.filter(.....)

I have always considered it to be good practice, and I use most of them a lot throughout my applications.

The problem is: These imports that are being used mostly for querying are stating to get in the way of my models' relations structure. Meaning: It's becoming more and more frequent that I cannot create properties for querying without creating circular import issues.

Is my approach correct? Is there a better way to encapsulate these queries? What do you usually do?

Thanks for your help.


Solution

  • I don't see why you need the properties at all, let alone the imports.

    If you're filtering some other model based on the current one, that must mean you have a relation to that model. And if you have a relation, then you should be using the automatic backwards relation. So rather than SomeOtherModel.objects.filter(blah=self), you should be doing self.someothermodel_set.all().