Python 如何用抽象模型定义外键关系?

Python 如何用抽象模型定义外键关系?,python,django,class,inheritance,django-models,Python,Django,Class,Inheritance,Django Models,有此代码: class Part: name = models.CharField( _("Name of part"), max_length=255, help_text=_("Name of the part.") class Meta: verbose_name = _("Part") verbose_name_plural = _("Parts") abstract = T

有此代码:

class Part:
    name = models.CharField(
        _("Name of part"),
        max_length=255,
        help_text=_("Name of the part.")

    class Meta:
        verbose_name = _("Part")
        verbose_name_plural = _("Parts")
        abstract = True


class Book(Part):
    isbn = models.CharField(
        help_text=_("The ISBN of the book"),
        max_length=15
    )
class StorageItem(models.Model):
    part = models.ForeignKey(
        Part,
        help_text=_("The part stored at this spot.")
    )
我的模特。我下一步需要链接到基本对象。使用此代码完成:

class Part:
    name = models.CharField(
        _("Name of part"),
        max_length=255,
        help_text=_("Name of the part.")

    class Meta:
        verbose_name = _("Part")
        verbose_name_plural = _("Parts")
        abstract = True


class Book(Part):
    isbn = models.CharField(
        help_text=_("The ISBN of the book"),
        max_length=15
    )
class StorageItem(models.Model):
    part = models.ForeignKey(
        Part,
        help_text=_("The part stored at this spot.")
    )
我收到以下错误消息:

错误:StorageItem.part:(fields.E300)字段定义 与型号“零件”的关系,该型号未安装或 抽象的


将对象链接到一组从一个基类派生的不同类的正确方法是什么

不幸的是,无法向抽象模型添加
ForeignKeys
。绕过此限制的一种方法是使用
GenericForeignKey

class StorageItem(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
然后,您可以按如下方式使用GenericForeignKey:

book = Book.objects.create(name='test', isbn='-')
item = StorageItem(content_object=book)
item.save()
item.content_object # <Book>
book=book.objects.create(name='test',isbn='-')
项目=存储项目(内容\对象=书本)
item.save()
item.content_object#
快速解释其工作原理:

  • content\u type
    存储泛型外键指向的模型
  • object\u id
    存储模型的id
  • content\u object
    是直接访问链接外键对象的快捷方式
这些文档提供了有关如何使用此功能的附加信息

编辑


经过进一步研究,它看起来也可以做你想做的事。

看起来django_多态性就是我最后想要的。不确定这是否是几个月内最好的一次,但到目前为止;)