【问题标题】:Generic Foreign Keys in Django AdminDjango Admin 中的通用外键
【发布时间】:2015-02-22 06:53:33
【问题描述】:

是否可以在 Django 管理中按 GenericForeignKey 对象标题进行过滤?

我想按程序名称过滤,NonSupportedProgram.titleSupportedProgram.title (list_filter = (SOME FIELD HERE)),但不知道怎么做?

models.py

class FullCitation(models.Model):
    # the software to which this citation belongs
    # either a supported software program or a non-supported software program
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

class NonSupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')

class SupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')

【问题讨论】:

  • 不,不一样,因为我在这里尝试使用GenericForeignKey 字段作为ModelAdmin.list_filter 和/或ModelAdmin.search_fields 中的参数。我不知道如何(或是否可能)使用 ModelAdmin 的搜索和/或过滤方法按我的 GenericForeignKey 对象的名称搜索/过滤...?

标签: django django-admin generic-foreign-key


【解决方案1】:

也许您可以使用 SimpleListFilter 并定义自己的查询集,以便获得自己的结果。

更多信息在这里: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter

class YourCustomListFilter(admin.SimpleListFilter):
   title = 'By Program Name'
   parameter_name = 'program'

   def lookups(self, request, model_admin):
       return(
           ('supported','Supported Programs'),
           ('nonsupported', 'Non-Supported Programs')
       )

   def queryset(self, request, queryset):
        if self.value() == 'supported':
            return queryset.filter(supported__isnull=False)
        if self.value() == 'nonsupported':
            return queryset.filter(nonsupported__isnull=False)

admin.py
list_filter = (YourCustomListFilter,)

您需要在 GenericRelation 声明中添加 related_query_name='supported' 和 related_query_name='nonsupported' 以允许从相关对象进行查询。

有关在此处查询 GenericRelations 的更多信息: https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#reverse-generic-relations

这应该是对正确方向的一点推动。

【讨论】:

    【解决方案2】:

    我认为合适的一种方法如下:

    您可以将模型更改为以下内容:

    class FullCitaton(models.Model):
        # Any Model Fields you want...
        program = ForeignKey('Program')
    
    class Program(models.Model):
        title = models.CharField(max_length=256, blank = True)
        is_supported = models.NullBooleanField()
    

    请注意,SupportedProgramNonSupportedProgram 现在都在同一个 Progam 模型中。区分它们的方法是通过 is_supported NullBoolean 字段。 然后,您所要做的就是使用标题字段查询Program 模型。 现在,也许您没有这样做,因为您有另一个我现在无法看到的问题。但是,无论如何,这应该可行。

    干杯!

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 1970-01-01
      • 2021-06-13
      • 2012-09-16
      • 1970-01-01
      • 2014-06-19
      • 2015-10-29
      • 2012-02-19
      • 2014-03-16
      相关资源
      最近更新 更多