I would like to know if there is a way to include/import the models.py from the project directory to multiple apps without copying the model in each app. Thank you!
-
Could you explain why do you need this? It's not quite clear to me what you mean by "include/import".Ludwik Trammer– Ludwik Trammer2014-07-08 09:25:21 +00:00Commented Jul 8, 2014 at 9:25
-
Well, I may have 5-6 apps in my project. And I don't want to copy each model in my app. What I want to know is that if you could import the models.py directly from project folder.mihai– mihai2014-07-08 09:36:36 +00:00Commented Jul 8, 2014 at 9:36
-
Well, have you tried? What happened? I don't see any difficult problem here...Seb D.– Seb D.2014-07-08 09:47:18 +00:00Commented Jul 8, 2014 at 9:47
-
Yes, I've tried. It gave me "No module named xxxxxx.models". Can you please explain me how would you do it? Thanks!mihai– mihai2014-07-08 09:50:51 +00:00Commented Jul 8, 2014 at 9:50
-
@LudwikTrammer Thank you for your response. I've watched that already. I did partitioned my project in apps corectly. Guess is not possible. Was loking for something like "from projectname.models import Product" to write in one of my app's views.pymihai– mihai2014-07-08 09:55:38 +00:00Commented Jul 8, 2014 at 9:55
3 Answers
Every app must have its own models.py present in the app folder.You have models.py in an app folder you can write the following import statement in any file of your project:
from myapp.models import model_to_import
If you have models.py outside any app folder or any other folder, then make sure that folder contains an (with two underscores)init(with two underscores).py file and just write the following in the file you want to import:
from folder_name import models
from models import model_to_import
1 Comment
You are not meant to put models directly on a project level in Django. Every model have to be associated with a particular app. On the other hand you can import models between apps.
If you feel a need for a project level models it just means you haven't partitioned your functionality into apps properly. There shouldn't be any reason to have "project level models" (or "project level views" for that matter). You just need to split the functionality into separate apps.
Let's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generating timetables, and yet another one for an internal message board, etc.. Every app defines its own models (there are no "project level models"), but apps can import each others models (so message board posts can have a ForeignKey field pointing at student from the "students" app).