如何在Django admin中使用ContentTypes在两个应用程序之间的ForeignKey上使用filter_horizo​​ntal?

时间:2016-01-29 06:44:40

标签: python django django-models django-admin

假设我有一个名为Pantry的应用程序,它可以连接到我可能出现的任何其他应用程序。为了保持应用程序解耦,通过关系模型LinkedItem使用泛型关系,该模型将Ingredients模型连接到Pantry之外的应用程序。

我希望通用关系另一端的内容,比如一个名为Bakery的应用程序,能够使用Ingredients做一个filter_horizo​​ntal。

食品储藏室 models.py

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields

class Ingredient(models.Model):
   '''
   Model containing all the ingredients, their slugs, and their descriptions
   '''
   name = models.CharField(unique=True, max_length=100)
   slug = models.SlugField(unique=True, max_length=100)
   description = models.CharField(max_length=300)

   # method to return the name of the db entry
   def __str__(self):
      return self.name

class LinkedItem(models.Model):
   '''
   Model that links ingredients to various other content models
   '''
   content_type = models.ForeignKey(ContentType)
   object_id = models.PositiveIntegerField()
   content_object = fields.GenericForeignKey('content_type', 'object_id')

   ingredient = models.ForeignKey(Ingredient)

   # method to return the name of the db entry
   def __str__(self):
      return self.ingredient.name

   # defines options for the model itself
   class Meta:
     unique_together = (('content_type','object_id'))    # prevents duplicates

面包 admin.py

from django.contrib import admin
from bakery.models import Cake

class CakeAdmin(admin.ModelAdmin):
   filter_horizontal = ('') # what to put here so ingredients show up?

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为这是GenericRelation的用途,因此您需要在Cake模型中添加一个并在CakeAdmin中使用它的名称。

但是,如果您不希望以M2M fields are not supported for relations with intermediary models进行大量解决方法,则需要使用Inlines。