小编Mat*_*ore的帖子

根据外键中的字段过滤Django admin中的list_filter

我想通过外键指向的表中的字段过滤我的list_filters之一.

我的模特:

class Organisation(models.Model):
    name = models.CharField()
    COMPANY = 'COMPANY'
    CHARITY = 'CHARITY'
    ORG_CHOICES = (
        (COMPANY, 'COMPANY'),
        (CHARITY, 'CHARITY'),
        )
    type = models.CharField(choices = ORG_CHOICES)

class Issue(models.Model):
   name = models.CharField
   charity = models.ForeignKey(Organisation)
Run Code Online (Sandbox Code Playgroud)

我想放入IssueAdmin:

list_filter = (charity)
Run Code Online (Sandbox Code Playgroud)

并为此提供慈善机构清单.目前,它只列出了组织模型中的所有内容,包括慈善机构和公司.例如,我现在在过滤器中获取此列表:

oxfam
yamaha
greenpeace
microsoft
Run Code Online (Sandbox Code Playgroud)

当我想要一个列出的过滤器:

oxfam
greenpeace
Run Code Online (Sandbox Code Playgroud)

我可以通过将组织表分成两个表(慈善机构和公司)来解决这个问题,但这感觉不对.

似乎SimpleListFilter应该可以工作,但到目前为止我还没有运气.基本上我想要使用以下过滤器并返回过滤器的慈善机构列表:

Organisation.objects.filter(type = 'CHARITY')
Run Code Online (Sandbox Code Playgroud)

我(差)尝试过滤器:

class CharityFilter(SimpleListFilter):
    title = _('Charity')
    parameter = _('charity__type')
    def lookups(self, request, model_admin):
        return Organisation.objects.filter(type = 'CHARITY')

    def queryset(self, request, queryset):
        if not self.value() is not None:
            return queryset.filter(type …
Run Code Online (Sandbox Code Playgroud)

django django-admin

4
推荐指数
2
解决办法
1万
查看次数

标签 统计

django ×1

django-admin ×1