【问题标题】:How to define a foreign key relation with an abstract model?如何用抽象模型定义外键关系?
【发布时间】:2016-01-24 15:41:29
【问题描述】:

拥有此代码:

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)字段定义 与模型“零件”的关系,该模型要么未安装,要么已安装 摘要。

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

【问题讨论】:

    标签: python django class inheritance django-models


    【解决方案1】:

    很遗憾,无法将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 也可以做你想做的事。

    【讨论】:

    • 看起来 django_polymorphic 是我最后想要的。不确定它是否会是几个月内最好的,但到目前为止;)
    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 2011-12-14
    • 2010-10-23
    • 2021-10-17
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2011-07-23
    相关资源
    最近更新 更多