从django list_filter中删除重复项
问题描述:
我在django管理员中使用相关对象中的字段上的列表过滤器。
I'm using a list filter in django admin on a field in a related object.
class A(models.Model):
#..
pass
class B(models.Model):
fk = models.ForeignKey(A)
val models.CharField(max_length=1)
在 A
的管理员中,我试图 list_filter
on B__val ,但结果是重复 A c $ c列出每个
B
满足过滤器值。
In the admin for A
, I'm trying to list_filter
on B__val
, but the result is duplicate A
's listed for each B
satisfying the filter value.
是否有一种简单的方法来截取查询结果以删除重复项?
Is there an easy way to intercept the query result to remove the duplicates?
答
管理员确实尝试添加 .distinct()
,但是由于某种原因错过了(必须是错误
The admin source indeed tries to add .distinct()
, but misses it on this for some reason (must be a bug?).
我得到以下所需的行为:
I get the behaviour I'm looking for with the following:
class NoDuplicates(ChangeList):
def __init__(self, *args):
super(NoDuplicates,self).__init__(*args)
def get_query_set(self):
return super(NoDuplicates,self).get_query_set().distinct()
class AAdmin(admin.ModelAdmin):
def get_changelist(self, request, **kwargs):
return NoDuplicates
list_filter = [ B__val ]