1

我有这些基于类的 ListView,我想按日期过滤。我有一个简单的 mixin 来显示 filterform,效果很好:

class MonthYearFormMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MonthYearFormMixin, self).get_context_data(**kwargs)
        context['monthyearform'] = MonthYearForm(self.request.GET)
        return context

我想扩展这个 mixin 的功能以包括查询集过滤,但是我的模型有不同的日期字段需要过滤,一个可能是 start_date,另一个可能是 invoice_date。当然有人可能会说,“将它们全部重命名为'日期'”,但这并不代表我的模型,此外,我可能有一个带有 start_date 和 end_date 的模型,但只想过滤 start_date。以下是我的看法:

class SentList(MonthYearFormMixin, ListView):
    model = Sent
    context_object_name = 'object'
    template_name = 'sent_list.html'

    def get_queryset(self):
        qs = self.model.objects.all()
        if 'month' in self.request.GET:
            if int(self.request.GET['month']) > 0:
                qs = qs.filter(start_date__month=self.request.GET['month'])
        if 'year' in self.request.GET:
            if int(self.request.GET['year']) > 0:
                qs = qs.filter(start_date__year=self.request.GET['year'])
        return qs

class ReceivedList(MonthYearFormMixin, ListView):
    model = Received
    context_object_name = 'object'
    template_name = 'received_list.html'

    def get_queryset(self):
        qs = self.model.objects.all()
        if 'month' in self.request.GET:
            if int(self.request.GET['month']) > 0:
                qs = qs.filter(invoice_date__month=self.request.GET['month'])
        if 'year' in self.request.GET:
            if int(self.request.GET['year']) > 0:
                qs = qs.filter(invoice_date__year=self.request.GET['year'])
        return qs

唯一不同的是日期字段的名称,因此不得不重复此代码令人沮丧。

4

1 回答 1

0

为什么不创建一个名为的成员变量date_field_name,用于存储应由 QuerySet 处理器 mixin 处理的字段名称的名称?

该列表将在使用 mixin 的类中定义。

就像是

class MonthYearFormMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MonthYearFormMixin, self).get_context_data(**kwargs)
        context['monthyearform'] = MonthYearForm(self.request.GET)
        return context

    def get_queryset(self):
        qs = self.model.objects.all()
        if 'month' in self.request.GET:
            if int(self.request.GET['month']) > 0:
                kwargs = {('%s__month' % self.date_field_name): self.request.GET['month']}
                qs = qs.filter(**kwargs)
        if 'year' in self.request.GET:
            if int(self.request.GET['year']) > 0:
                kwargs = {('%s__year' % self.date_field_name): self.request.GET['year']}
                qs = qs.filter(**kwargs)
    return qs

您的视图将如下所示:

class SentList(MonthYearFormMixin, ListView):
    model = Sent
    context_object_name = 'object'
    template_name = 'sent_list.html'
    date_field_name = 'start_date'
于 2013-04-12T15:35:20.540 回答