2014-10-08 88 views
0

我想要在数据库设计上建立一个层次结构,如Elmasri & Navathe的“数据库系统基础知识”中所述。Django模型类型的多表继承不起作用

这意味着当我有许多类/表共享的信息时,我可以将它放在主父表中,并在子表中使用主表ID作为外键,这是一种弱实体。我试过使用抽象和多重继承(这最后一个不让我指定OneToOneField,不知道在哪里可以找到这个在Django文档)。

我的例子就在这里(每类一个表):

'''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的相当多的初学者,但我已经看过的文件和证明一些事情与抽象=真在人,而不是已经成功我现在想我应该乱用初始化构造函数用于获取超构建并在此之后构建子类。

我不知道选择正确的路径,但绝对不想改变数据库设计。请帮忙。

在此先感谢。

回答

1

你不需要在你的模型中有ID; Django自动处理它。你也不应该使用骆驼案件。换句话说:personId应该是person_id,并且无论如何都不是必需的 - 只需将其删除即可。

通常我会避免使用ORM进行非抽象继承。

我真的不明白你想实现什么,但我会建议2层的方法(对人,校友,教授,等等),根据您的需要:

1.摘要继承:

class Person: 
    class Meta: 
     abstract = True 

    # here you put all the common columns 

然后:

class Alumni(Person): 
    # the other columns - specific to alumn 

通过这样做,你必须每个子类人的一个表:Alumn,教授等

2.使用组成:

class Alumn: 
    person = models.ForeignKey(Person, null=True, related_name="alumni_at") 
    university = ... 

class Professor: 
    person = models.ForeignKey(Person, null=True, related_name="professor_at") 
    university = ... 

这样,你可以这样做:

bob = Person.objects.create(first_name="bob", ...) 
Alumn.objects.create(person=bob, university="univ 1") 
Professor.objects.create(person=bob, university="univ 2") 
Alumn.objects.create(person=bob, university="univ 2")