【问题标题】:Python Classes Foreign Keys InheritancePython 类外键继承
【发布时间】:2013-08-14 17:59:36
【问题描述】:

我想知道 - 是否可以继承这样的类?

例如,我有 2 个抽象类:

    class Book(models.Model):
        name = models.TextField()

        class Meta:
            abstract = True

    class Page(models.Model)
        num = models.IntegerField()
        book = models.ForeignKey('Book')

        class Meta:
            abstract = True

所以 - 我想为这两个创建继承类,让它们成为 BigBookBigBookPage

但是如果我这样做了,python 对我说,我的 FK 字段不能与抽象模型有关系。而且我找不到在继承模型中重新定义 FK 的方法。那么我是否必须只在继承模型中创建外键 - 而不是父母?

如果我有相同的模型方法,使用在父模型中定义的外键......我必须将它们移动到每个孩子 - 这样他们就可以使用他们的外键?

【问题讨论】:

    标签: python inheritance django-models foreign-keys django-1.4


    【解决方案1】:

    听起来您想将 Book 标记为 proxy=True。见proxy models。它将创建一个书本模型,但也让您拥有从它继承的其他模型,让您自定义子类的功能。

    class Book(models.Model):
        class Meta:
            proxy = True
    
    class BigBook(Book):
        # BigBook properties go here.
    

    【讨论】:

      猜你喜欢
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多