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

标签 python django python-3.x django-models django-admin

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

我可以在 Django 中为 LinkedItem 的管理员显示一个 filter_horizo​​ntal。现在,我希望通用关系另一端的内容(比如名为 Bakery 的应用程序)能够对配料执行 filter_horizo​​ntal。

茶水间 模型.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/

相关文章:

python - Django 用户注册刚刚停止工作

Python:双重排序

python - 以编程方式创建函数规范

python - 函数调用不起作用 python

django - FormView 未在 Django 中保存数据

python - 通过允许容差匹配两个包含略有不同的浮点值的列表

javascript - Sphinx 和 JavaScript 文档工作流

python - 是否有 django 应用程序为服务器上的文件提供文件选择器?

python - 按字符串中的数字对字符串列表进行排序?

python - 要求用户提供输入,直到他们给出有效的答复