- Django Design Patterns and Best Practices
- Arun Ravindran
- 181字
- 2021-06-25 21:32:05
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.
- Go Web編程
- HTML5+CSS3+JavaScript從入門到精通:上冊(微課精編版·第2版)
- Java多線程編程實戰指南:設計模式篇(第2版)
- JavaScript前端開發模塊化教程
- C語言程序設計案例教程(第2版)
- Manga Studio Ex 5 Cookbook
- JMeter 性能測試實戰(第2版)
- Web Development with Django Cookbook
- 羅克韋爾ControlLogix系統應用技術
- TypeScript項目開發實戰
- 信息技術應用基礎
- Drupal 8 Module Development
- PHP 7+MySQL 8動態網站開發從入門到精通(視頻教學版)
- Working with Odoo
- 從Java到Web程序設計教程