繁体   English   中英

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

[英]How to define a foreign key relation with an abstract model?

具有以下代码:

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)字段定义了与模型'Part'的关系,该关系未安装或为抽象。

将对象链接到一组都源自一个基类的不同类的正确方法是什么?

不幸的是,不可能将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>

快速说明其工作原理:

  • content_type存储通用外键指向的模型
  • object_id存储模型的ID
  • content_object是直接访问链接的外键对象的快捷方式

该文档提供了有关如何使用此https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#generic-relations的其他信息

编辑

经过进一步的研究,看起来django_polymorphic也可能会做您想要的。

暂无
暂无

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

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