Django Admin中的通用外键

时间:2015-02-22 06:53:34

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

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

我想按计划名称进行过滤,NonSupportedProgram.titleSupportedProgram.titlelist_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')

2 个答案:

答案 0 :(得分: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

这应该是朝着正确的方向发展。

答案 1 :(得分:0)

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

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

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模型。 现在,也许你没有这样做,因为你有另一个我现在无法看到的问题。但是,无论如何,这应该有效。

干杯!