Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django project models.py versus app models.py

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.

like image 306
nrshapiro Avatar asked Apr 09 '10 20:04

nrshapiro


People also ask

What is the difference between Django project and Django app?

1 Answer. The difference between Project and App in Django is that the Project could be defined as the entire application, containing apps to perform specific tasks. And Apps are within the Project that is self-sufficient in a project and are designed to perform specific tasks.

What is Django models py?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .

How many apps should I have Django?

Django comes with six built-in apps that we can examine.

What constitutes a Django app?

A Django application is a Python package that is specifically intended for use in a Django project. An application may use common Django conventions, such as having models , tests , urls , and views submodules.


1 Answers

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.

like image 74
Ludwik Trammer Avatar answered Nov 07 '22 12:11

Ludwik Trammer