ajwood
ajwood

Reputation: 19037

Remove duplicates from django list_filter

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)

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?

Upvotes: 2

Views: 2120

Answers (1)

ajwood
ajwood

Reputation: 19037

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 ]

Upvotes: 2

Related Questions