使用Django的ORM进行模型继承方法

moj*_*bro 3 python django django-models model-inheritance

我想将事件存储在我正在讨论的Web应用程序中,我对每种方法的利弊都非常不确定 - 广泛使用继承或以更适度的方式使用继承.

例:

class Event(models.Model):
    moment = models.DateTimeField()

class UserEvent(Event):
    user = models.ForeignKey(User)
    class Meta:
        abstract = True

class UserRegistrationEvent(UserEvent):
    pass # Nothing to add really, the name of the class indicates it's type

class UserCancellationEvent(UserEvent):
    reason = models.CharField()
Run Code Online (Sandbox Code Playgroud)

感觉就像我正在疯狂地创建数据库表.它需要很多连接来选择出来并且可能使查询复杂化.但我认为它的设计感觉很好.

使用只有更多字段的"更平坦"模型会更合理吗?

class Event(models.Model):
    moment = models.DateTimeField()
    user = models.ForeignKey(User, blank=True, null=True)
    type = models.CharField() # 'Registration', 'Cancellation' ...
    reason = models.CharField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

感谢您对此的评论,任何人.

菲利普

Ale*_*lli 6

Flat优于嵌套.在这种情况下,我没有看到"深度继承"真的会给你带来任何东西:我会选择更平坦的模型作为更简单,更简洁的设计,具有更好的性能特征和易于访问.

  • 对于这个具体的例子,我完全同意。例如,只有当 UserRegistrationEvent 上有一大堆不适用于常规事件的数据字段时,我才会开始考虑继承。即使在那种情况下,我也会考虑使用抽象基本模型而不是多表继承。 (2认同)