简体   繁体   中英

django admin - how to reverse filter on multiple foreign keys

Django 1.8: As shown below, I have Location model with a foreign key to the Study model. I want to display Studies that include country='usa' and is_active=True. The problem with using the default filter is that if I have:

study1:
country='usa', is_active=False
country='canada', is_active=True

The filter displays this study but it should not so here is what I've tried:

##### 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)

The filter is not displaying anything. Any ideas how to achieve what I want? I've also read the doc about RelatedFieldListFilter but it's pretty confusing.

I figured out. Just a minor bug in the lookups. I had to pick the country at index zero: Correction:

    return tuple([(country[0], _('active in %s' % country[0])) for country in unique_countries])

I hope this sample helps others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM