简体   繁体   English

django admin-如何对多个外键反向过滤

[英]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. Django 1.8:如下所示,我具有Location模型,其中带有Study模型的外键。 I want to display Studies that include country='usa' and is_active=True. 我想显示包含country ='usa'和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. 我也阅读了有关RelatedFieldListFilter的文档,但这很令人困惑。

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. 我希望此示例对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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