使用__range和F的Django查询
我正在尝试编写一个基于特定日期的查询。比方说,我有三个数据分贝使用__range和F的Django查询
target_date = 28th of october
today = 23rd of october
data one
publish_date = 26th of october
data two
publish_date = 24th of october
data three
publish_date = target_date # 28th of october
我的查询需要获取目标日期前三天或更少天的所有数据。由于目标日期是10月28日,因此应该提取第26,27和28天(目标日期)范围内的任何数据。
查询
MyModel.objects.filter(
publish_date__range=[F('publish_date'), F('publish_date') - timedelta(days=3)]
)
的target_date变化基于行数据。 我收到意想不到的结果。
第一:“我收到了意想不到的结果。”错误的方式来了解您的问题
第二:任何方式,你会在过滤器的问题,因为你在最大日期后添加最短日期。
第三:你其中的SQL将条款的样子:
WHERE "publish_date" BETWEEN F(publish_date) AND F(publish_date) - DurationValue(3 days, 0:00:00)
应用于每一行,所以你会得到空的查询设置
最后,我可以看到你可以尝试简单的方法:
target_date = MyModel.objects.filter(HERE_YOUR_RULE).first().publish_date
from_date = target_date - timedelta(days=3)
MyModel.objects.filter(publish_date__range=[from_date, target_date])
不要忘记改变HERE_YOUR_RULE
,希望它有帮助。
试试这个过滤器:
reference_date = MyModel.objects \
.filter(user=some_user_receiving_email) \
.order_by('-is_published')[0].is_published
queryset_to_include_in_email = MyModel.objects.filter(
publish_date__gte=reference_date - timedelta(days=3),
publish_date__lte=reference_date
)
target_date可以根据行来变化,你能解释一下关于reference_date的更多信息吗?谢谢 –
为了让我明白,除了'publish_date'字段之外,表中还有'target_date'字段吗? – davecaputo
没有target_date,我只有publish_date,我想获取将在publish_date发布前3天发布的所有数据并将电子邮件发送给用户。所以publish_date根据用户输入的内容而有所不同 –
MyModel.objects.
filter(publish_date__range=
[F('publish_date'), F('publish_date') + timedelta(days=3)])
这将获取其published_date在公布日期,三天之间的范围在发布后的所有对象。
这对我不起作用,因为它只会使用第一个数据作为参考,target_date可能因数据行而异。可能我没有解释得很好 –