- Django Design Patterns and Best Practices
- Arun Ravindran
- 216字
- 2021-06-25 21:32:09
Problem details
Fat models, thin views is an adage commonly told to Django beginners. Ideally, your views should not contain anything other than presentation logic.
However, over time, pieces of code that cannot be placed anywhere else tend to go into models. Soon, models become a dump yard for the code.
Consider refactoring out a Service object if your model contains code for any of the following:
- Interactions with external services, for example, checking whether the user is eligible to get a SuperHeroProfile with a web service
- Helper tasks that do not deal with the database, for example, generating a short URL or random captcha for a user
- Making a short-lived object without a database state, for example, creating a JSON response for an AJAX call
- Functionality spanning multiple model instances yet do not belong to anyone
- Long-running tasks such as Celery tasks
Models in Django follow the Active Record pattern, that is, each class instance corresponds to a row in the database table. Ideally, they encapsulate both database access and application (or domain) logic. However, keep the application logic minimal.
While testing, if we find ourselves mocking the database even while not using it, then we need to consider breaking up the model class. A Service object is recommended in such situations.
- Practical Data Analysis Cookbook
- JavaScript高效圖形編程
- Oracle 12c中文版數據庫管理、應用與開發實踐教程 (清華電腦學堂)
- 高級C/C++編譯技術(典藏版)
- Python時間序列預測
- PHP+Ajax+jQuery網站開發項目式教程
- Flask Web開發:基于Python的Web應用開發實戰(第2版)
- scikit-learn Cookbook(Second Edition)
- Python Programming for Arduino
- 數據科學中的實用統計學(第2版)
- 3D Printing Designs:The Sun Puzzle
- React.js實戰
- ROS Robotics Projects
- Learning ClojureScript
- Go語言Hyperledger區塊鏈開發實戰