我想通过外键指向的表中的一个字段来过滤我的list_filters之一。在Django admin中根据外键中的字段过滤list_filter
我的模型:
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)
我想放在IssueAdmin:
list_filter = (charity)
而且为提供慈善机构的名单。目前它只列出了组织模型中的所有内容,包括慈善机构和公司。例如,我在那一刻得到这个列表过滤:
oxfam
yamaha
greenpeace
microsoft
当我想要一个过滤器,列出:
oxfam
greenpeace
我可以分裂组织表分成两个表解决这个(慈善和公司),但感觉不对。
看起来像SimpleListFilter应该可以工作,但到目前为止我还没有任何运气。基本上我想什么用途以下过滤器和返回慈善机构的列表过滤:在过滤器
Organisation.objects.filter(type = 'CHARITY')
我的(差)的尝试:
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 = 'CHARITY')
else:
return queryset
任何一个能帮助我吗?
工作。我必须将.distinct()添加到查找返回的末尾,否则它会列出相同时间的慈善组织100次。但是,否则,它完美的作品。谢谢。 –