views:

171

answers:

3

I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck.

I took a database that I use (a copy of course) and generated the conceptual schema as a django model using inspectdb. I did this at the project level, and presumed then I could write apps using subschemas in the applications for that project.

But generalizing the tutorial, they define the model in the application's model.py. If I did that, I would be repeating the model (or part of it) that's already at the project level, which seems like a mistake and a maintenance issue.

So how, in Django style, do I use the project schema (or parts of it) without redefining it in the application's models.py?

Thanks in advance.

+2  A: 

Django models can only reside in applications, not in project itself. By default manage.py inspectdb outputs content of the models.py file and it's up to you to put it in the right place.

In your case it would be easier to put whole thing in one app and later split it in the places where it would make sense.

I'm not sure what's the state with the current version, but before presence of models module in package was indication that this is django application and can be put in INSTALLED_APPS list.

Łukasz
+5  A: 

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).

See also James Bennett's "writing reusable Django applications" presentation from DjangoCon 2008.

Ludwik Trammer
Very interesting and educative talk! James also mentioned the worldonline sites only have `settings.py` and `urls.py`. The rest are reusable apps in the python path of apache.
vdboor
+1  A: 
  • A model should only be defined once in a Django project

  • The model needs to exist in an app under the project

  • You can access other app's models by importing them

  • If you need to "add on" to an existing model it can be inherited from (see: multi table inheritance). This is fairly simple but if you're just starting out you may want to leave that for later.

T. Stone