简体   繁体   English

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

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

Having this code: 具有以下代码:

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
    )

for my models. 为我的模特。 I next step I need to link to the basic object. 下一步,我需要链接到基本对象。 Done with this code: 完成此代码:

class StorageItem(models.Model):
    part = models.ForeignKey(
        Part,
        help_text=_("The part stored at this spot.")
    )

I'm getting this error message: 我收到此错误消息:

ERRORS: StorageItem.part: (fields.E300) Field defines a relation with model 'Part', which is either not installed, or is abstract. 错误:StorageItem.part:(fields.E300)字段定义了与模型'Part'的关系,该关系未安装或为抽象。

What is the correct approach to link an object to a group of different classes all derived from one base class? 将对象链接到一组都源自一个基类的不同类的正确方法是什么?

Unfortunately it's not possible to add ForeignKeys to abstract models. 不幸的是,不可能将ForeignKeys添加到抽象模型中。 One way to get around this limitation is to use GenericForeignKey : 克服此限制的一种方法是使用GenericForeignKey

class StorageItem(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

Then you can use the GenericForeignKey as follows: 然后,您可以按以下方式使用GenericForeignKey:

book = Book.objects.create(name='test', isbn='-')
item = StorageItem(content_object=book)
item.save()
item.content_object # <Book>

A quick explanation of how this works: 快速说明其工作原理:

  • content_type stores the model that generic foreign key points to content_type存储通用外键指向的模型
  • object_id stores the id of the model object_id存储模型的ID
  • content_object is a shortcut for directly accessing the linked foreign key object content_object是直接访问链接的外键对象的快捷方式

The docs provide additional information on how to use this https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#generic-relations 该文档提供了有关如何使用此https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#generic-relations的其他信息

Edit 编辑

Upon further research, it looks like django_polymorphic may also do what you want. 经过进一步的研究,看起来django_polymorphic也可能会做您想要的。

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

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