How to Combine Date and Time Fields into DateTime

2019-08-29 05:42发布

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)

This also doesn't work;

    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)

What django does is as follows:

...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")) AT TIME ZONE) /3600 AS ...

What I am expecting is:

...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")AT TIME ZONE)) / 3600 AS ...

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?

Thanks.

1条回答
不美不萌又怎样
2楼-- · 2019-08-29 06:22

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.

查看更多
登录 后发表回答