2016-01-24 87 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