Avoiding circular dependencies in Django applications

While working on my Django-based projects, I always try to follow Django's approach to reusable applications - I try to separate my applications from each other and especially try to avoid cross-references, but sometimes this doesn't seem to be possible.

Consider a simple example with two applications: articles and users. The “Articles” application defines the model of the article, the presentation of the list of articles and viewing of one article, the user application defines the user model and the presentation of the user profile. The article refers to the user from the author’s field, therefore the application-article clearly depends on the user-application, which is in order.

But when it comes to the user profile, I want to show the latest articles created by the user (and may be the last articles viewed by the user) on this page, but this makes the application-app aware of the article-app, which is what I'm trying to avoid.

Obviously, I can try to push all such links to the template level, but it still does not solve the problem completely and at the same time can be very inefficient in terms of database queries.

What do you guys do in such cases?

+3
source share
3 answers

"" "", , . . , , , : " 5 ".

, . , .

+9

( ) - , django, , .

, , , - Django , . , , : -)

+1

It seems that in this case, the dependence of users on articles is in the method, and not in the field. (Regardless of whether it is a model method, a model class method, or a manager method). If so, you can do lazy import of articles inside the method. By the time this import is complete, .models users will be fully loaded, so even if it is a cyclic import, it will not cause problems. The "import users" operator in articles does not have to reload users and have a full user namespace.

-1
source

Source: https://habr.com/ru/post/1787290/


All Articles