Django管理中是否可以按GenericForeignKey
对象标题进行筛选?
我想按程序名称过滤,NonSupportedProgram.title
或SupportedProgram.title
(list_filter = (SOME FIELD HERE)
),但不知道如何过滤?
型号.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')
也许您可以使用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-一般关系
这应该是朝着正确的方向迈出的一小步。
我认为合适的一种方式是:
您可以将您的型号更改为以下型号:
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()
请注意,SupportedProgram
和NonSupportedProgram
现在都在同一个Progam
模型中。区别它们的方法是通过is_supported
NullBoolean
字段。然后,您所要做的就是使用title字段查询Program
模型。现在,也许你没有这样做,因为你有另一个问题,我现在看不到。但是,无论如何,这应该奏效。
干杯!