【问题标题】:For extended information, should I use Django's Multi-table Inheritance or an explicit OneToOneField对于扩展信息,我应该使用 Django 的多表继承还是显式 OneToOneField
【发布时间】:2011-11-23 18:34:48
【问题描述】:

我的模型中有一些字段不会总是填写(例如,项目结束前的实际完成日期和成本)。正因为如此,我想我应该把模型分成两部分:

  1. 模型 #1:包含经常搜索和始终完成的字段的密集表
  2. 模型 #2:包含不常搜索且并非总是完成的字段的稀疏表

问题

  1. 我是否正确地将其拆分为两个模型/表?
  2. 我应该使用 Django 的多表继承,还是应该明确定义 OneToOneField?为什么?

配置

  • Django 版本 1.3.1

型号

使用 Django 的多表继承

class Project(models.Model):
    project_number = models.SlugField(max_length=5, blank=False,
            primary_key=True)
    budgeted_costs = models.DecimalField(max_digits=10, decimal_places=2)

class ProjectExtendedInformation(Project):
    submitted_on = models.DateField(auto_now_add=True)
    actual_completion_date = models.DateField(blank=True, null=True)
    actual_project_costs = models.DecimalField(max_digits=10, decimal_places=2,
            blank=True, null=True)

使用显式OneToOneField

class Project(models.Model):
    project_number = models.SlugField(max_length=5, blank=False,
            primary_key=True)
    budgeted_costs = models.DecimalField(max_digits=10, decimal_places=2)

class ProjectExtendedInformation(models.Model):
    project = models.OneToOneField(CapExProject, primary_key=True)
    submitted_on = models.DateField(auto_now_add=True)
    actual_completion_date = models.DateField(blank=True, null=True)
    actual_project_costs = models.DecimalField(max_digits=10, decimal_places=2,
            blank=True, null=True)

【问题讨论】:

  • 老实说,我认为拆分您的模型没有意义,原因如下:您声明不经常搜索且并不总是完成的字段也是“稀疏”的。这降低了拆分模型的价值,可能无法弥补额外的复杂性。当然,您比我更了解您的数据,所以请谨慎采纳我的建议。

标签: django database-design django-models


【解决方案1】:

你在这里基本上是在处理苹果和苹果。 Django 的 MTI(多表继承)实现使用隐式 OneToOneField。

【讨论】:

  • 如果这是苹果和苹果,一个比另一个更喜欢吗?
  • 视情况而定。如果有一个明确的 is-a 关系正在发生。就像class Dog(Animal),那么你应该使用MTI(如果需要的话。其他一些继承形式可能更合适)。但是,在auth.User 之类的情况下,UserProfile 并不是真正的User 类型,所以OneToOneField 更有意义。但是,最大的警告是使用UserProfile,因为User 无法更改。否则,简单地向User 添加额外的字段会更合适。
猜你喜欢
  • 2014-11-03
  • 2012-11-13
  • 2013-09-26
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2011-10-28
  • 2018-07-23
相关资源
最近更新 更多