从本质上讲,我的问题是,无论我过滤什么,以下设置都会在管理页面中返回整个查询集。
模型.py
from django.db import models
class Booking(models.model):
client = models.ForeignKey(Client)
reference = models.CharField(max_length=100)
....
def __unicode__(self):
return self.reference
class Client(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(null=True, blank=True)
...
def __unicode__(self):
return self.name
def total_bookings(self):
return len(self.booking_set.all())
def bookings0(self):
if self.total_bookings() == 0:
return True
def bookings1(self):
if self.total_bookings() == 1:
return True
def bookings2(self):
if self.total_bookings() == 2:
return True
def bookings3plus(self):
if self.total_bookings() > 2:
return True
...
管理员.py
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from clakes.models import Client, Booking ...
class BookingAdmin(admin.ModelAdmin):
...
class NumBookingListFilter(SimpleListFilter):
title = _('Number of Bookings')
parameter_name = 'numofbooks'
def lookups(self, request, model_admin):
return (
('no', _('No Bookings')),
('1', _('One')),
('2', _('Two')),
('3plus', _('Three or more')),
)
def queryset(self, request, queryset):
if self.value() == 'no':
return [x for x in queryset if x.bookings0()]
if self.value() == '1':
return [x for x in queryset if x.bookings1()]
if self.value() == '2':
return [x for x in queryset if x.bookings2()]
if self.value() == '3plus':
return [x for x in queryset if x.bookings3plus()]
class ClientAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'total_bookings', ...)
search_fields = ['name']
list_filter = (NumBookingListFilter,)
...
...
admin.site.register(Client, ClientAdmin)
admin.site.register(Booking, BookingAdmin)
有人可以向我解释我哪里出错了。The filter appears on the 'Client' admin page as expected, but when one option is selected the filter does not work - the url changes to http:.../client/?e=1 but no filtering has occurred as it should. 我的列表理解在 shell 中工作 - 例如 [x for x in queryset if x.bookings1()] 返回正确的客户端列表。
我很乐意考虑使用管理器或其他方式的不同方法。谁好心回答,请不要只指出文档,因为我现在已经花了几个小时阅读和重新阅读它,所以如果我错过了这一点,那是由于缺乏理解而不是努力。