我想按照 Elmasri & Navathe 的“数据库系统基础”中的描述对数据库设计进行层次结构。
这意味着当我有一些为许多类/表共享的信息时,我可以将它放在主父表中,并使用主表 ID 作为子表中的外键,这是一种弱实体。
我尝试使用抽象和多表继承(最后一个不允许我指定 OneToOneField,不知道在 django docs 哪里可以找到它)。
我的例子就在这里(每个班级一张桌子):
'''I would like this to be abstract, because I will never instantiate it,
but could be not if needed'''
class Person(models.Model):
personId = models.IntegerField(primary_key=True)
name = models.CharField(max_length=45)
surname = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=45, blank=True)
phone = models.CharField(max_length=15, blank=True)
class Meta:
managed = False
db_table = 'person'
class Alumn(Person):
# Maybe this one down should be OneToOne.
# alumnId == personId always true for the same real world guy
alumnId = models.ForeignKey('Person', db_column='alumnId', primary_key=True)
comments = models.CharField(max_length=255, blank=True)
class Meta:
managed = False
db_table = 'alumn'
# There are more child classes (Client, Professor, etc....)
# but for the example this is enough
我的目标是实现在 DB 中创建一个 Alumn,只需两句话:
a = Alumn(personId=1,name='Joe', [...more params...] , alumnId=1, comments='Some comments' )
a.save()
并让这两行插入两行:一行用于 Person,另一行用于 Alumn。上面这段代码中的 alumnId 属性可以省略,因为它总是与 personId 相同(我告诉过你,就像一个弱实体)。
我是 django 的初学者,但我查看了文档并用 abstract=True in Person 证明了一些事情,但没有成功我想现在我应该弄乱init构造函数来构建超类,然后构建儿童班。
我不知道选择的正确路径,但绝对不想改变数据库设计。请帮忙。
提前致谢。