Remove duplicates from django list_filter

I am using a list filter in django admin in a field in a linked object.

class A(models.Model): #.. pass class B(models.Model): fk = models.ForeignKey(A) val models.CharField(max_length=1) 

In admin for A I try list_filter on B__val , but the result is a duplicate of A for each B that matches the filter value.

Is there an easy way to intercept the query result to remove duplicates?

0
source share
1 answer

The admin source is really trying to add .distinct() , but for some reason skips it for this reason (should there be an error?).

I get the behavior 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 ] 
+1
source

Source: https://habr.com/ru/post/1488976/


All Articles