2016-10-03 69 views
3

我有兩個模型。父母和孩子。因爲孩子和家長有不同的領域,我不得不將他們分開,而不是有一個模特兒。 因爲一個孩子應該有一個父親和一個母親,我有兩個獨立的父親和母親在不同的模型。 到目前爲止:django foreignKey指多個表

class Father(models.Model): 
    name = models.CharField(max_length=50) 
    ... 
class Mother(models.Model): 
    name = models.CharField(max_length=50) 
    ... 
class Child(models.Model): 
    name = models.CharField(max_length=50) 
    ... 
    father=models.ForeignKey(Father) 
    mother... 

應當更好地設計,但我不是一個職業。

現在我需要有另一種健康模式。是否可以建立一個模型,哪些領域屬於兒童,父親或母親?或者我應該爲每個像孩子健康,父親健康等一樣制定一個健康模型? thnx提前

+1

看看[Django的通用關係(https://docs.djangoproject.com/en/1.10/ref/contrib/contenttypes/#generic-relations),可能是它可以幫助你 – devxplorer

回答

1

您可以創建抽象模型,例如, HumanAbstract

class HumanAbstract(models.Model): 
    class Meta: 
     abstract = True 

    name = models.CharField(max_length=50) 
    rest_common_fields = ... 

然後你FatherMotherChild可以從HumanAbstract繼承。由於MetaHumanAbstractabstract = True它不會在數據庫中創建。

Docs關於抽象類。

此外,您可以消除FatherMother型號,並只創建Parent型號。

class Parent(HumanAbstract): 
    pass 

class Child(HumanAbstract): 
    father = models.ForeignKey(Parent) 
    mother = models.ForeignKey(Parent) 
    ... 

UPDATE

@SergeyZherevchuk是正確的約GenericForeignKey,你可以簡單地集成了,這將是最好的選擇。

class HealthModel(models.Model): 
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) 
    object_id = models.PositiveIntegerField() 
    content_object = GenericForeignKey('content_type', 'object_id') 
    ...