繁体   English   中英

Django模型的多表继承无效

[英]Django models kind of multi-table inheritance not working

我想按照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中创建校友:

a = Alumn(personId=1,name='Joe', [...more params...] , alumnId=1, comments='Some comments' )
a.save()

并让这两行插入两行:一行用于“人”,另一行用于“校友”。 此处的这段代码中的alumnId属性可以省略,因为它始终与personId相同(我告诉过您,就像一个虚弱的实体一样)。

我是django的初学者,但是我看了看文档,并用abstract = True in Person证明了一些事情,但没有成功,我想现在我应该与init构造函数混为一谈,以构建超类,然后再构建儿童班。

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

提前致谢。

您的模型中不需要ID。 Django自动处理它。 另外,您不应该使用骆驼箱。 换句话说:personId应该是person_id,无论如何都不需要-只需将其删除即可。

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

我不太了解您要实现的目标,但是我建议两种方法(针对Person,Alumni,Professional等),具体取决于您的需求:

1.抽象继承:

class Person:
    class Meta:
        abstract = True

    # here you put all the common columns

然后:

class Alumni(Person):
    # the other columns - specific to 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM