Splitting django models.py
into multiple files
M is bigger than V and C in Django
In Django, models are classes that provide an object-oriented way of dealing with databases. Typically, each class refers to a database table and each attribute refers to a database column. You can make queries to these tables using an automatically generated API.
Splitting models.py into multiple files
Like most components of Django, a large models.py
file can be split up into multiple files within a package. A package is implemented as a directory, which can contain multiple files, one of which must be a specially named file called __init__.py
. This file can be empty, but should exist.
All definitions that can be exposed at package level must be defined in __init__.py
with global scope. For example, if we split models.py into individual classes, in corresponding files inside the models subdirectory such as postable.py
, post.py
, and comment.py
, then the directory structure would look as follows:
To ensure that all the models are imported correctly, __init__.py
should have the following lines.
Now you can import models.Post
as previously.
Any other code in the __init__.py
file will be run when the package is imported. Hence, it is the ideal place for any package-level initialization code.
Reference
-
Django Design Patterns and Best Practices by Arun Ravindran : Second Edition - pg 39
-
Django refactoring — how to split admin.py and models.py in 3 steps
- Divide Models.py into smaller parts