2016-01-24 91 views
1

有了这个代码:如何用抽象模型定义外键关系?

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.") 
    ) 

我得到这个错误消息::

ERRORS:StorageItem.part:(fields.E300)字段定义 与模型 '部件' 的关系,这与此代码完成要么没有安装,要么是抽象的 。

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

回答

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存储通用外键的标识模型
  • content_object是一个快捷方式直接访问链接的外键对象

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

编辑

在进一步的研究更多的信息,它看起来像django_polymorphic也可以做你想做的。

+0

它看起来像django_polymorphic是我最后寻找的。不确定是否会在几个月内成为最好的,但到目前为止;) – frlan