Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django get a reference to a model in another app

I imagined this would be relatively straight forward but I cannot find a solution. I have two apps 'library' and 'counts'. I want to get a reference to a model in 'library' from inside 'counts'. Both apps are registered in settings.INSTALLED_APPS. My project is in a virtualenv named 'slideaudit'. In that is the project folder named 'src'. My apps live under 'src' as well as the conf folder. I imagined I would write something similar to: from project_name.app_name.models import model_name

Whilst there appears to be considerable posts on the issue I haven't found one that does the job. Any ideas please?

like image 285
Chas Avatar asked Dec 14 '22 10:12

Chas


1 Answers

It depends on what you mean by reference:

  1. If you want simply to do: from app1.models import MyModel1 this does not need any special configuration: just add app1 to INSTALLED_APPS and django will directly recognize it.
  2. But if you mean by reference Foreign Key you don't event need to import your model, you do just as follow:

    class NyModel2(model.Model):
        field = models.ForeignKey("app1.MyModel1", verbose_name="my_model1", related_name="my_models2")
    
    • django will understand that you need model MyModel1 from app1
    • related_name attribute specifies the name of the reverse relation which means my_model1.my_models2.all() return all the MyModel2 instance that have my_model1 as foreign key.
like image 170
Dhia Avatar answered Jan 01 '23 22:01

Dhia