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

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.

主站蜘蛛池模板: 金华市| 苍溪县| 萍乡市| 英山县| 曲麻莱县| 临邑县| 四平市| 瓦房店市| 叙永县| 蓝田县| 青海省| 灵台县| 宝应县| 沙坪坝区| 余干县| 怀仁县| 沙洋县| 会泽县| 宿迁市| 娱乐| 利川市| 平远县| 南江县| 视频| 盘锦市| 仙居县| 丹东市| 西乌珠穆沁旗| 丹江口市| 尉氏县| 疏附县| 宜州市| 万宁市| 加查县| 祁门县| 冀州市| 岳池县| 民县| 前郭尔| 理塘县| 孟连|