假设我有一个名为 Pantry 的应用程序,它可以连接到我可能使用的任何其他应用程序。为了保持应用程序解耦,通过模型 LinkedItem 使用通用关系,它将 Ingredients 模型连接到 Pantry 外部的应用程序。
我可以在 Django 中为 LinkedItem 的管理员显示一个 filter_horizontal。现在,我希望通用关系另一端的内容(比如名为 Bakery 的应用程序)能够对配料执行 filter_horizontal。
茶水间 模型.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?
有什么想法吗?
最佳答案
一个解决方案是创建一个 GenericTabularInline对于 LinkedItem 并在显示上设置一些限制以避免如下所示的重复:
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]
关于python - 如何使用 Django 管理员的 ContentTypes 在两个应用程序之间访问 ManyToManyField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077299/