如何使用Django管理员的ContentTypes访问两个应用程序之间的ManyToManyField?

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

我可以在Django中为LinkedItem的管理员制作一个filter_horizo​​ntal.现在,我希望通用关系的另一端的内容,比如一个名为Bakery的应用程序,能够使用成分进行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.ManyToManyField(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?

有任何想法吗?

最佳答案 一个解决方案是为LinkedItem创建一个 GenericTabularInline并对显示设置一些限制以避免重复,如下所示:

from django.contrib.contenttypes.admin import GenericTabularInline

class LinkedItemAdmin(GenericTabularInline):
    model = LinkedItem

    # choosing the field and display
    field = ['ingredient']
    filter_horizontal = ['ingredient']

    # These help with removing some potential issues in the admin
    extra = 0
    min_num = 1
    max_num = 1
    can_delete = False

然后在CakeAdmin中,我可以做到这一点,使成分出现.

class CakeAdmin(admin.ModelAdmin):
    inlines = [LinkedItemAdmin]
点赞