官术网_书友最值得收藏!

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

主站蜘蛛池模板: 额尔古纳市| 麻栗坡县| 慈利县| 阿克苏市| 昆山市| 吉水县| 新乡市| 谷城县| 安乡县| 饶河县| 泰兴市| 东丰县| 景东| 镇原县| 水富县| 梅州市| 玉龙| 永年县| 观塘区| 黎川县| 女性| 崇仁县| 新绛县| 麟游县| 扬州市| 玛纳斯县| 会同县| 综艺| 桂林市| 威信县| 九台市| 赞皇县| 夏邑县| 会泽县| 肃南| 巴马| 通州区| 库尔勒市| 班玛县| 青龙| 斗六市|