我必须获得两个datetime
字段的差异,但一个是纯日期时间字段,另一个是日期和时间的组合。
我尝试过这个:
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 的作用如下:
...(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 执行相同的操作?
谢谢。
最佳答案
我已经解决了这个问题并得到了答案。只需要 ExpressionWrapper
的 output
参数中的 DurationField()
而不是 DateTimeField()
。这是代码:
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)
这样我就可以解决之前遇到的问题。这可能对其他人有帮助。
关于django - 如何在 Django F 表达式中将日期和时间字段合并为日期时间字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56631679/