- Django Design Patterns and Best Practices
- Arun Ravindran
- 191字
- 2021-06-25 21:32:07
Model mixins
Model mixins are abstract classes that can be added as a parent class of a model. Python supports multiple inheritances, unlike other languages such as Java. Hence, you can list any number of parent classes for a model.
Mixins ought to be orthogonal and easily composable. Drop in a mixin to the list of base classes and they should work. In this regard, they are more similar in behavior to composition rather than inheritance.
Smaller mixins are better. Whenever a mixin becomes large and violates the single responsibility principle, consider refactoring it into smaller classes. Let a mixin do one thing and do it well.
In our previous example, the model mixin used to update created and modified time can be easily factored out, as shown in the following code:
class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now =True) class Meta: abstract = True class Postable(TimeStampedModel): message = models.TextField(max_length=500) ... class Meta: abstract = True class Post(Postable): ... class Comment(Postable): ...
We have two base classes now. However, the functionality is clearly separated. The mixin can be separated into its own module and reused in other contexts.
- FreeSWITCH 1.6 Cookbook
- 精通Python設計模式(第2版)
- 硅谷Python工程師面試指南:數據結構、算法與系統設計
- Python深度學習原理、算法與案例
- TMS320LF240x芯片原理、設計及應用
- Troubleshooting Citrix XenApp?
- 進入IT企業必讀的324個Java面試題
- 從零開始:C語言快速入門教程
- Java RESTful Web Service實戰
- Monitoring Docker
- 一步一步學Spring Boot:微服務項目實戰(第2版)
- RESTful Web API Design with Node.js
- Python Django Web從入門到項目實戰(視頻版)
- Spring Boot 2+Thymeleaf企業應用實戰
- Web程序設計與架構