Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import models from one app to another app in Django?

Tags:

python

django

I am trying to reference a model (Person) from one app, in the views-file of another app. Unfortunately, I get an "unresolved reference"-error. Is it possible to reference models from other apps in Django? If so, what am I doing wrong?

Let me demonstrate with an example:

The image below shows my project. I am currently in the views.py (marked in green), in the app called "autocomplete". I want to reference a person-model in the file "models.py" (marked in red), that belongs to the app "resultregistration". However, I get the error "Unresolved reference Person", even though the class Person does exist in models.py

enter image description here

The file settings.py is in the athlitikos/athlitikos - folder, and manage.py is in only athlitikos (as seen in the image below)

enter image description here

Any help would be strongly appreciated!

Edit: I now tried running "from ..resultregistration.models import Person", because I saw that what I did in the screenshot was obviously wrong. However, then I get the error message " attempted relative import beyond top-level package"

Thank you for your time!

like image 384
Nora Avatar asked Sep 27 '17 09:09

Nora


People also ask

How import all models in Django?

To do this, create a directory called /«project»/«app_name»/models , inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py . You should read about Python modules to understand this.


1 Answers

If the resultregistration app is in the project directory (the one containing manage.py) then you shouldn't include the project name athlitikos in the import at all. Try the following:

from resultregistration.models import Person
like image 144
Alasdair Avatar answered Nov 05 '22 18:11

Alasdair