如何在Django F表达式中将日期和时间字段合并为DateTime字段 [英] How to Combine Date and Time Fields into DateTime Field in Django F Expression

查看:264
本文介绍了如何在Django F表达式中将日期和时间字段合并为DateTime字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须得到两个 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 输出参数中的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆