Skip to content

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:

models/
├── comment.py
├── __init__.py
├── postable.py
└── post.py

To ensure that all the models are imported correctly, __init__.py should have the following lines.

from postable import Postable
from post import Post
from comment import Comment

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