2014-10-08 108 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")