Circular dependency importing models from custom QuerySet

I’m trying to write a custom QuerySet method in a querysets.py file inside an app. The problem is my method needs references to other models to perform Subqueries and do some joins.

I can’t import these models because they are in the same models.py file where I’m importing this queryset to use with .as_manager().

What is the correct way to do this? You could argue that this logic should maybe belong in a Manager, but that doesn’t really address my circular dependencies issue.

This QuerySet is a mixin that will be reused by more than one model in more than one app.

1 Like

I finally decided, at least for now, to import the model from inside the method where I need it and that solves the circular dependency issue.

I’m not sure if this a good practice, so I’d still like to hear if someone has any other recommendation.

Thanks!

It’s both good practice and the only way to handle these kinds of model imports. You’ll often see it in models.py files if other models are needed, too. It’s way better and more readable than any alternative that I’m aware of. You could find a way around it, but then you’d have to wash your eyes for a while, and Future You would have a hard time figuring out what you did and why.

Thanks! I thought about alternatives but nothing really clean came to mind. I’ll stick with this solution.