Question

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.

Was it helpful?

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

OTHER TIPS

Is there a better way to encapsulate these queries?

Actually, you shouldn't let the circular dependency eat you, go removing it up instead. This will increase your access to the database in the later stage of the project.You can remove the circular imports by redefining your structure at this stage only , otherwise it will be too late to refactor and correct where you were wrong.

What do you usually do?

Basically, it is not what others do.It depends on what your application is scoped of. If your application is long term app, then what you are doing is wrong. Just make a repository kind of thing which will be available to all the code and the code can access it whenever needed without any circular imports , that is without any dependency.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top