Django查询过滤ISO周数 [英] Django queryset filtering by ISO week number
问题描述
我有一个包含 datefield
的模型。我正在尝试获取包含当前周的模型的查询集(从星期一开始)。
所以自Django datefield $ c我假定通过使用
.isocalendar()
来简单的 datetime.date
模型。在逻辑上,这正是我想要的,而没有在本周的时间里没有额外的比较和计算。
所以我想做的本质上是强制 .filter
语句在这个逻辑中表现:
如果model.date.isocalendar()[2] == datetime.date.today()。isocalendar()[2]
...
但是如何将其写入过滤器语句?
.filter(model__date__isocalendar = datetime.date.today()。isocalendar())
将给出错误的结果(与今天不比本周相比) / p>
作为挖掘真正的 http:// docs。 python.org/library/datetime.html 我没有注意到任何其他周日选项...
文档注意事项:
date.isocalendar()返回一个3元组(ISO年,ISO周号,ISO
工作日)。
更新:
虽然我不喜欢使用范围的解决方案是最好的选择。
然而,在我的情况下,我创建了一个变量,标记一周的开始,只是看起来更大或相等的价值,因为如果我正在寻找一周的比赛。如果给出一周的数量将需要两端。
today = datetime.date.today()
monday = today - datetime.timedelta(days = today.weekday())
... \
.filter(date__gte = monday)
你不会这样做。记住,这不仅仅是Python支持的问题,Django必须将过滤器传递给数据库,数据库不支持这种复杂的日期计算。 可以使用 __范围
,但开始日期和结束日期。
I have a model that contains datefield
. I'm trying to get query set of that model that contains current week (starts on Monday).
So since Django datefield
contains simple datetime.date
model I assumed to filter by using .isocalendar()
. Logically it's exactly what I want without no extra comparisons and calculations by current week day.
So what I want to do essentially is force .filter
statement to behave in this logic:
if model.date.isocalendar()[2] == datetime.date.today().isocalendar()[2]
...
Yet how to write it inside filter statement?
.filter(model__date__isocalendar=datetime.date.today().isocalendar())
will give wrong results (same as comparing to today not this week).
As digging true http://docs.python.org/library/datetime.html I have not noticed any other week day options...
Note from documentation:
date.isocalendar() Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
Update:
Although I disliked the solution of using ranges yet it's the best option. However in my case I made a variable that marks the beginning of the week and just look greater or equal value because if I'm looking for a matches for current week. In case of giving the number of the week It would require both ends.
today = datetime.date.today()
monday = today - datetime.timedelta(days=today.weekday())
... \
.filter(date__gte=monday)
You're not going to be able to do this. Remember it's not just an issue of what Python supports, Django has to communicate the filter to the database, and the database doesn't support such complex date calculations. You can use __range
, though, with a start date and end date.
这篇关于Django查询过滤ISO周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!