在Python Django查询集中排除周末

0 投票
3 回答
586 浏览
提问于 2025-04-17 16:27

我想要筛选一些日期,排除掉周末的日期。 我已经有了一个包含周末日期的列表。

我想创建一个查询,来过滤掉这些日期。 在我的模型中有一个日期字段,内容是

Class Sample(models.Model)
    date=models.DateField()

weekends = [2, 3, 9, 10, 16, 17, 23, 24]
Sample.objects.filter(date__month=month).exclude(date__day=weekends)

我可以用一个循环来实现这个功能,不过那样代码会很糟糕…… 我在想有没有什么一行就能完成的过滤方法。

3 个回答

1

最后,我搞明白了这个问题。exclude(date__day__in=weekends) 这个写法不管用。我也不知道为什么,可能是因为这个复杂的查找在用“in”查询的时候出问题了。

所以我做的是用那些天创建了一些日期。然后做了类似这样的操作:

Sample.objects.filter(Q(date__month=month)).exclude(Q(date__in=weekends))
2

你可以使用 in 操作符:

Sample.objects.filter(Q(date__month=month)).exclude(Q(date__day__in=weekends))
2

你可以使用 IN 这个条件。

Sample.objects.filter(date__month=month).exclude(date__day__in = weekends)

这是 Django 的 DateField 的源代码:

def get_prep_lookup(self, lookup_type, value):
    # For "__month", "__day", and "__week_day" lookups, convert the value
    # to an int so the database backend always sees a consistent type.
    if lookup_type in ('month', 'day', 'week_day'):
        return int(value)

所以理论上来说,__day 应该可以用。你也可以试着把你的字段名称从 date 改成像 created_date 这样的名字,以避免名字冲突。

撰写回答