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

Solution details

Abstract inheritance is an elegant solution which uses special Abstract base classes to share data and behavior among models. When you define an abstract base class in Django, which are not the same as abstract base classes (ABCs) in Python, it does not create any corresponding table in the database. Instead, these fields are created in the derived non-abstract classes.

Accessing abstract base class fields doesn't need a JOIN statement. The resulting tables are also self-contained with managed fields. Due to these advantages, most Django projects use abstract base classes to implement common fields or methods.

Limitations of abstract models are as follows:

  • They cannot have a Foreign key or many-to-many field from another model
  • They cannot be instantiated or saved
  • They cannot be directly used in a query since it doesn't have a manager

Here is how the post and comment classes can be initially designed with an abstract base class:

class Postable(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    modified = models.DateTimeField(auto_now=True) 
    message = models.TextField(max_length=500) 
 
    class Meta: 
        abstract = True 
 
 
class Post(Postable): 
    ... 
 
 
class Comment(Postable): 
    ... 

To turn a model into an abstract base class, you will need to mention abstract = True in its inner Meta class. Here, Postable is an abstract base class. However, it is not very reusable.

In fact, if there was a class that had just the created and modified field, then we can reuse that timestamp functionality in nearly any model needing a timestamp. In such cases, we usually define a model mixin.

主站蜘蛛池模板: 苍溪县| 徐州市| 施甸县| 兴海县| 济南市| 读书| 仙桃市| 泽库县| 太仆寺旗| 白沙| 沙河市| 芮城县| 义乌市| 富锦市| 焦作市| 荆州市| 开封县| 探索| 镇雄县| 丹巴县| 利川市| 渑池县| 灵石县| 邢台县| 岳池县| 开江县| 县级市| 鹤岗市| 辛集市| 遂溪县| 兴城市| 嘉黎县| 万盛区| 藁城市| 莱芜市| 建阳市| 赤水市| 安溪县| 南昌市| 泊头市| 夹江县|