Django 1.8: 如下所示,我的Location模型带有Study模型的外键。 我想显示包含country ='usa'和is_active = True的研究。 使用默认过滤器的问题是,如果我有:
study1:
country='usa', is_active=False
country='canada', is_active=True
过滤器显示了这项研究,但它不应该是我尝试的那样:
##### models.py:
class Study(models.Model):
title = models.CharField(max_length=30)
def __unicode__(self):
return self.title
class Location(models.Model):
is_active = models.BooleanField()
country = models.CharField(max_length=30)
study = models.ForeignKey(Study, related_name='location')
def __unicode__(self):
return self.country
##### admin.py
class ActiveCountryFilter(admin.SimpleListFilter):
title = _('Active Country Filter')
parameter_name = 'country'
def lookups(self, request, model_admin):
# distinct keyword is not supported on sqlite
unique_countries = []
if DATABASES['default']['ENGINE'].endswith('sqlite3'):
countries = Location.objects.values_list('country')
for country in countries:
if country not in unique_countries:
unique_countries.append(country)
else:
unique_countries = Location.objects.distinct('country').values_list('country')
return tuple([(country, _('active in %s' % country)) for country in unique_countries])
def queryset(self, request, queryset):
if self.value():
return queryset.filter(location__country=self.value(), location__is_active=True)
else:
return queryset
@admin.register(Study)
class StudyAdmin(admin.ModelAdmin):
list_display = ('title',)
list_filter = ('location__country', ActiveCountryFilter)
过滤器未显示任何内容。 任何想法如何实现我想要的? 我还阅读了有关RelatedFieldListFilter的文档,但这很令人困惑。
答案 0 :(得分:0)
return tuple([(country[0], _('active in %s' % country[0])) for country in unique_countries])
我希望这个样本可以帮助其他人。