2

I have django model like this:

from django.db import models
from django_countries.fields import CountryField

class Profile(models.Model):
    name = models.CharField(max_length=200)
    country = CountryField()

In the admin, I want to filter by country. But when I add country to the list_filter, I get a huge list of ALL the countries on the right. Is there a way to limit the filter list to contain only countries that actually have at least assigned Profiles?

This is similar, but not a duplicate of, Can I make list_filter in django admin to only show referenced ForeignKeys?. Note that here I am using django_countries, not a ForeignKey, which makes this question different.

Note: I am using Django 1.7, so I don't have access to RelatedOnlyFieldListFilter.

Community
  • 1
  • 1
a06e
  • 18,594
  • 33
  • 93
  • 169

1 Answers1

1
class CountryListFilter(admin.SimpleListFilter):
    title = 'Country'
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        countries = set([t.country for t in model_admin.model.objects.filter(country!=None)])
        return [(country, country)for country in countries]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(country=self.value())
        else:
            return queryset
Dawn T Cherian
  • 4,968
  • 3
  • 24
  • 35