我想在数据库设计上建立一个层次结构,如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中创建一名校友,只需说两句话:
^{pr2}$让这两行插入两行:一行给人,一行给校友。这个片段中的alumnId属性可以省略,因为它总是与personId相同(我告诉过你,就像一个弱实体)。在
我是django的初学者,但是我看过文档,并且亲自用abstract=True证明了一些事情,但是没有成功,现在我想我应该使用init构造函数来构建超类,然后再构建子类。在
我不知道选择正确的路径,但肯定不想改变数据库的设计。请帮忙。在
提前谢谢。在
模型中不需要有id;Django会自动处理它。你也不能用驼色的箱子。换句话说:personId应该是personId,而且无论如何都不是必需的-只需删除它。在
一般来说,我避免使用ORM进行非抽象继承。在
我真的不明白你想要达到什么目标,但我建议你根据自己的需要推荐两种方法(针对个人、校友、教授等):
1。抽象继承:
然后:
^{pr2}$等等
通过这样做,每个子类型的人都有一个表:校友、教授等
2。使用构图:
您可以这样做:
^{4}$相关问题 更多 >
编程相关推荐