0

我想按照 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 中创建一个 Alumn,只需两句话:

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

并让这两行插入两行:一行用于 Person,另一行用于 Alumn。上面这段代码中的 alumnId 属性可以省略,因为它总是与 personId 相同(我告诉过你,就像一个弱实体)。

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

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

提前致谢。

4

1 回答 1

1

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

一般来说,我避免使用 ORM 进行非抽象继承。

我不太了解您想要达到的目标,但我会根据您的需要建议 2 种方法(对于 Person、Alumni、Professor 等):

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")
于 2014-10-09T02:43:52.200 回答