【问题标题】:Django admin: Filter by country. Show only non-empty countries?Django 管理员:按国家/地区过滤。仅显示非空白国家/地区?
【发布时间】:2015-11-27 02:38:25
【问题描述】:

我有这样的 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。

【问题讨论】:

    标签: django django-admin django-countries


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多