我想将事件存储在我正在讨论的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()
感觉就像我正在疯狂地创建数据库表。它需要很多连接来选择出来并且可能使查询复杂化。但我认为它的设计感觉很好。
使用只有更多字段的“更扁平”的模型会更合理吗?
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)
感谢您对此的评论,任何人。
菲利普
答案 0 :(得分:6)
Flat is better than nested。在这种情况下,我没有看到“深度继承”真的会给你带来任何东西:我会选择更平坦的模型作为更简单,更简洁的设计,具有更好的性能特征和易于访问。
答案 1 :(得分:1)
您可能想尝试Abstract base models。这实现了没有连接的继承,只是为派生类创建表,包含父模型和派生模型的字段。这将允许您保留嵌套设计,而不会对所有这些连接造成性能损失。