如何在Django F表达式中将日期和时间字段合并为DateTime字段 [英] How to Combine Date and Time Fields into DateTime Field in Django F Expression
问题描述
我必须得到两个 datetime
字段的差额,但一个是纯datetime字段,另一个是日期和时间的组合。
我尝试了这个:
I have to get the difference of two datetime
fields but one is pure datetime field and other is a combination of date and time.
I tried this one:
qs = Foo.objects.filter(
bar__baz_id=self.kwargs['baz_pk'],
)
start_datetime = ExpressionWrapper((F('x__date') + F('x__start')), output_field=DateTimeField())
qs = qs.annotate(start_datetime=start_datetime)
before_start_wrapper = ExpressionWrapper(
F('start') - F('start_datetime'), # 'start' is datetime field on Foo, start_datetime is annotated field on Foo
output_field=DateTimeField()
)
before_start = Extract(before_start_wrapper, 'epoch')
qs = qs.annotate(before_start=before_start/3600)
这也不起作用;
qs = Foo.objects.filter(
bar__baz_id=self.kwargs['baz_pk'],
)
start_datetime = F('x__date') + F('x__start')
before_start_wrapper = ExpressionWrapper(
F('start') - F(start_datetime), # 'start' is datetime field on Foo, start_datetime is combined F expression
output_field=DateTimeField()
)
before_start = Extract(before_start_wrapper, 'epoch')
qs = qs.annotate(before_start=before_start/3600)
django的功能如下:
What django does is as follows:
...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")) AT TIME ZONE) /3600 AS ...
我期望的是:
...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")AT TIME ZONE)) / 3600 AS ...
请问有人可以提供解决方案吗? Django ORM?我知道我可以运行原始查询,但是想看看是否有一种方法可以对Django ORM进行同样的操作?
Can some one please provide the solution with Django ORM? I know I can run a raw query but wanted to look if there is a way to do the same with Django ORM?
谢谢。
推荐答案
我已经解决了该问题并得到了答案。只需要 ExpressionWrapper $ c $的
输出
参数中的 DurationField()
c>而不是 DateTimeField()
。下面是代码:
I have worked around the issue and got the answer. Only need the DurationField()
in the output
param of the ExpressionWrapper
instead of DateTimeField()
. Here is the code:
qs = Foo.objects.filter(
bar__baz_id=self.kwargs['baz_pk'],
)
start_datetime = F('x__date') + F('x__start')
before_start_wrapper = ExpressionWrapper(
F('start') - F(start_datetime), # 'start' is datetime field on Foo, start_datetime is combined F expression
output_field=DurationField()
)
before_start = Extract(before_start_wrapper, 'epoch')
qs = qs.annotate(before_start=before_start/3600)
通过这种方式我可以管理问题我早一点。这可能对其他人有帮助。
This way I got to manage the issue I had earlier. This might be helpful for someone else.
这篇关于如何在Django F表达式中将日期和时间字段合并为DateTime字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!