模型继承方法与Django的ORM [英] Model inheritance approach with Django's ORM

查看:207
本文介绍了模型继承方法与Django的ORM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将事件存储在Web应用程序中,我很愚蠢,我对每个方法的利弊感到不确定 - 广泛使用继承或以较温和的方式。

I want to store events in a web application I am fooling around with and I feel quite unsure about the pros and cons of each respective approach - using inheritance extensively or in a more modest manner.

示例:

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()

感觉像我正在创建数据库表,如疯狂。它需要大量的联接来选择事物,并可能使查询复杂化。但是它的设计感觉很好,我想。

It feels like I'm creating database tables like crazy. It would require alot of joins to select things out and might complicate querying. But it's design feels nice, I think.

使用更多字段的更平坦的模式会更合理吗?

Would it be more reasonable to use a "flatter" model that just has more fields?

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)

感谢您对此的任何意见。

Thanks for your comments on this, anyone.

Philip

推荐答案

平好比嵌套。在这种情况下,我并没有看到深度继承真的在为你买东西:我会以更简单,更简单的设计去更平坦的模式,具有更好的性能特点和便于访问。

Flat is better than nested. I don't see that the "deep inheritance" is really buying you anything in this case: I'd go for the flatter model as a simpler, plainer design, with likely better performance characteristics and ease of access.

这篇关于模型继承方法与Django的ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆