【问题标题】:How to use filter_horizontal on a ForeignKey between two apps using ContentTypes in Django admin?如何在 Django admin 中使用 ContentTypes 在两个应用程序之间的 ForeignKey 上使用 filter_horizo​​ntal?
【发布时间】:2016-05-06 19:54:07
【问题描述】:

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

我希望通用关系另一端的内容,比如一个名为 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.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?

有什么想法吗?

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

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

    但如果您不想像M2M fields are not supported for relations with intermediary models 那样做很多变通方法,则需要使用内联。

    【讨论】:

    • GenericRelation 不起作用,因为 filter_horizo​​ntal 需要 M2M 字段。你说的解决方法是什么?
    • 好吧,您一开始就没有 M2M 字段。如果您真的需要 filter_horizo​​ntal 小部件,请编写小部件自定义和自定义 CakeAdmin.save_model。或者使用框架并使用Inlines
    猜你喜欢
    • 2015-09-08
    • 2019-08-15
    • 2012-04-24
    • 2016-05-06
    • 2012-01-31
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多