Django SimpleListFilter双选项自定义查询

时间:2017-03-23 18:10:34

标签: python django django-admin

我正在尝试编写一个SimpleListFilter,它需要有2个select字段来选择过滤对象的当前状态,以及需要过滤的当前日期范围然后加入那些2在对象上创建自定义过滤器以获取所需属性的值。

当前问题是由第一个过滤器创建的,其中add是对网址的过滤,并且在应用第二个过滤器后不需要此过滤器。

我还尝试使用request.GET.pop('entered_state')弹出过滤器,但是python返回错误:

In [1]: request
Out[1]: <WSGIRequest: GET '/admin/requests/request/?entered_state=completed&entered_state_at=2_week'>

In [2]: request.GET.pop('entered_state')
AttributeError: This QueryDict instance is immutable

这是我到目前为止所做的:

class EnteredStateFilter(admin.SimpleListFilter):

   title = _('Entered State')
   parameter_name = 'entered_state'

   def lookups(self, request, model_admin):
       return (
          ('completed',  _('Completed')),
          ('denied',     _('Denied')),
          ('expired',    _('Expired')),
          ('cancelled',  _('Cancelled'))
        )

   def queryset(self, request, queryset):
       return queryset

class EnteredStateAtFilter(admin.SimpleListFilter):

title = _('Entered State at')
parameter_name = 'entered_state_at'

def lookups(self, request, model_admin):
    return (
        ('today',_('Today')),
        ('1_week',_('Past 7 days')),
        ('2_week',_('This month')),
        ('3_week',_('This year')),
    )


def queryset(self, request, queryset):
    entered_state = request.GET.get('entered_state')
    today = datetime.now().date()

    if entered_state != None:
        if self.value() == 'today':
            kwargs ={'entered_{}_at__date'.format(entered_state):today}
            return queryset.filter(**kwargs)
        elif self.value() == 'Past 7 days':
            kwargs ={'entered_{}_at__date__gte'.format(entered_state):today-relativedelta(weeks=1)}
            return queryset.filter(**kwargs)
        elif self.value() == 'Past month':
           kwargs ={'entered_{}_at__date__gte'.format(entered_state):today-relativedelta(months=1)}
           return queryset.filter(**kwargs)
        elif self.value() == 'Past year':
           kwargs ={'entered_{}_at__date__gte'.format(entered_state):today.replace(month=1, day=1)}
           return queryset.filter(**kwargs)

    return queryset

1 个答案:

答案 0 :(得分:0)

QueryDict实例是不可变的,因此如果要弹出它,则应将True设置为request.GET._mutable。但下面更好。

request.GET.get('entered_state')