4

I need to connect two apps in a Django project, but don't want to import models from the one into the other. Keeping them 'clean' will allow me to reuse them separately later on.

In this particular case, I need a many-to-many relation between two models in these separate apps. One solution would be to create a model in the main project app that defines foreign keys to both. Is this the Django way or is there a better solution?

Sven
  • 985
  • 1
  • 11
  • 27
  • If one app requires importing of modules from another app then there is no tidiness in it (because they are dependent). – Aamir Rind Dec 18 '12 at 00:12
  • 1
    some related questions: https://stackoverflow.com/q/4137287, https://stackoverflow.com/q/2054357, https://stackoverflow.com/q/49261290 – djvg Jun 10 '21 at 15:54

2 Answers2

4

Maybe you are looking for a kind of Mediator Pattern. If your apps don't need to know each other, one approach can be write another app that will know both.

Fernando Macedo
  • 2,518
  • 1
  • 24
  • 25
  • Yes, that's what I thought when I said I could put a model in the main project app. But I think I found something better and more Django-esque: [proxy model inheritance](https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models). That way I can keep the base app clean of any project-related dependencies and thus reusable, and put them instead into a "derived" app with proxy models. And of course, I will need to swap the base app with the derived app in settings/INSTALLED_APPS. – Sven Dec 18 '12 at 22:33
0

django-profiles, django-sorl, django- all work as a 'many-to-one' type relationship. When you choose to use on of these plugins/apps (and others), you will end up making your designed app dependant on on their presence.

Option 1: Considering the above... make one of the apps you intend to design generic enough that the dependency is only 1 way (hence, other apps will depend on it but not the other way around). This is what most django apps already do.

Option 2: If each of your apps shares a dependency amongst each another, then you'd probably make your life a lot easy to just keep it part of the same app/plug-in.

Chris
  • 491
  • 7
  • 14
  • thanks - Yes I don't mind if I dirty my project-specific apps, just the generic apps should stay clean. I tested the proxy mechanism and it fits my needs entirely, i.e. I can expand my generic app by the part that depends on the other apps. It's like inheritance for apps without dirtying the underlying data. – Sven Dec 24 '12 at 22:16