如何查询一天中某个小时之前在Django中创建的对象? [英] How do I query for objects created before a certain hour in a day in Django?
问题描述
在Django中,我试图仅将查询过滤到一天中某个小时之前创建的对象.我有一个名为"created_at"的日期时间字段,用于存储创建该对象的日期时间.
In Django, I am trying to filter my query only to objects that were created before a certain hour in the day. I have a datetime field called 'created_at' that stored the datetime from which that object was created.
我想做的是:
query = query.filter(created_at__hour__lte=10)
我希望获得上午10点之前创建的所有对象.但是,当我尝试该操作时,我得到一个:
Which I would expect to get all the objects that were created before 10am. However, when I try that I get a:
FieldError: Join on field 'created_at' not permitted. Did you misspell 'hour' for the lookup type?
我可以遍历每一天并获取当天的对象,但这似乎效率很低.有没有办法可以在单个查询中做到这一点?如果没有,那么运行这种过滤器的最快方法是什么?
I could loop through each day and get that day's objects, but that seems highly inefficient. Is there a way I can do this in a single query? If not, what is the fastest way to run this sort of filter?
推荐答案
__ hour
是查找类型,因此您不能将其与其他查找混合使用像 __ lte
这样的类型.您可以使用 Q
对象(例如EG)构造一个过滤器:
__hour
on a DateTimeField
is a lookup type, so you can't mix it with another lookup type like __lte
. You could construct a filter with Q
objects, EG:
before_ten = Q(created_at__hour=0)
for hour in range(1, 11):
before_ten = before_ten | Q(created_at__hour=hour)
query = query.filter(before_ten)
如果可以更改数据模型,则保存创建时间 TimeField
以及现有的 created_at
可能更方便.
If you can change your data model, it might be more convenient to save a creation time TimeField
as well as your existing created_at
.
这篇关于如何查询一天中某个小时之前在Django中创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!