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

Problem details

While designing models, you might find certain common attributes or behaviors shared across model classes. For example, a post and comment model needs to keep track of its created date and modified date. Manually copying and pasting the fields and their associated method is not a very DRY approach.

Since Django models are classes, object-oriented approaches such as composition and inheritance are possible solutions. However, compositions (by having a property that contains an instance of the shared class) will need an additional level of indirection to access fields.

Inheritance can get tricky. We can use a common base class for post and comments. However, there are three kinds of inheritance in Django: concrete, abstract, and proxy.

Concrete inheritance works by deriving from the base class just like you normally would in Python classes. However, in Django, this base class will be mapped into a separate table. Each time you access base fields, an implicit join is needed. This leads to horrible performance.

Proxy inheritance can only add new behavior to the parent class. You cannot add new fields. Hence, it is not very useful for this situation.

Finally, we are left with Abstract inheritance.

主站蜘蛛池模板: 黔南| 政和县| 山阳县| 乌兰浩特市| 秀山| 广德县| 日喀则市| 寻甸| 罗甸县| 边坝县| 苍溪县| 马关县| 新化县| 崇明县| 汉沽区| 军事| 修水县| 姜堰市| 绥宁县| 莱阳市| 金坛市| 商洛市| 杭锦旗| 凤冈县| 南安市| 乐亭县| 贵港市| 平顺县| 随州市| 阿克苏市| 福清市| 石家庄市| 宁强县| 遵化市| 寿光市| 台山市| 页游| 海伦市| 河南省| 吴旗县| 陆良县|