根据可选的开始日期和结束日期筛选queryset

时间:2021-07-14 18:04:10

I want to filter a queryset by a date range where both the start and end date are optional. Specifically,

我想通过一个日期范围来筛选一个queryset,其中开始日期和结束日期都是可选的。具体地说,

if dt_from:
    results = results.filter(date_modified__gte=dt_from)
if dt_until:
    results = results.filter(date_modified__lte=dt_until)

where dt_from and dt_until are each either datetime.datetime, datetime.date, or None. The documentation about the behaviour of chaining multiple filters is extremely confusing however (see Chaining multiple filter() in Django, is this a bug?), and I'm not sure that the above does what I think it does (it may OR the filters rather than ANDing them).

其中dt_from和dt_until分别是datetime。datetime,datetime。日期,或没有。关于链接多个过滤器的行为的文档是非常令人困惑的(参见Django中chaining多重过滤器(),这是一个bug吗?),我不确定上面是否做了我认为它做的事情(可能是过滤器,而不是对它们进行分析)。

Does the above code achieve what I want (i.e. AND the two filters) or is there another way I should do this?

上面的代码实现了我想要的(也就是两个过滤器),还是有另外一种方法我应该这样做?

1 个解决方案

#1


1  

I have a generic solution for this kind of problems. Reuse this custom queryset for all models

对于这类问题,我有一个通用的解决方案。对所有模型重用这个自定义的查询集

class MyQuerySet(models.QuerySet):

    def filter_if(self, **kwargs):
        new_kwargs = {a: b for (a, b) in kwargs.items() if b}
        return self.filter(new_kwargs)

results.filter_if(date_modified__gte=dt_from, date_modified__lte=dt_until)

#1


1  

I have a generic solution for this kind of problems. Reuse this custom queryset for all models

对于这类问题,我有一个通用的解决方案。对所有模型重用这个自定义的查询集

class MyQuerySet(models.QuerySet):

    def filter_if(self, **kwargs):
        new_kwargs = {a: b for (a, b) in kwargs.items() if b}
        return self.filter(new_kwargs)

results.filter_if(date_modified__gte=dt_from, date_modified__lte=dt_until)