我想通過外鍵指向的表中的一個字段來過濾我的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次。但是,否則,它完美的作品。謝謝。 –