我有这样的django模型:
from django.db import models
from django_countries.fields import CountryField
class Profile(models.Model):
name = models.CharField(max_length=200)
country = CountryField()
在管理员中,我想按国家/地区进行过滤。但是,当我向country
添加list_filter
时,我会在右侧列出所有国家/地区的大量列表。有没有办法限制过滤器列表只包含实际上至少分配了Profiles
的国家/地区?
这与Can I make list_filter in django admin to only show referenced ForeignKeys?类似,但不重复。请注意,我在这里使用django_countries
,而不是ForeignKey,这使得这个问题与众不同。
注意:我使用的是Django 1.7,因此我无法访问RelatedOnlyFieldListFilter。
答案 0 :(得分:0)
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
答案 1 :(得分:0)
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__isnull=False)])
return [(country, country.name)for country in countries]
def queryset(self, request, queryset):
if self.value():
return queryset.filter(country=self.value())
else:
return queryset