django - 如何在 Django F 表达式中将日期和时间字段合并为日期时间字段

标签 django postgresql django-models django-rest-framework django-orm

我必须获得两个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 执行相同的操作?

谢谢。

最佳答案

我已经解决了这个问题并得到了答案。只需要 ExpressionWrapperoutput 参数中的 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/

相关文章:

postgresql - 在 postgres 上使用索引进行慢速 sql 选择

python - 使用 : python manage. py [something] 或 ./manage.py [something] 有什么不同吗

python - boto3 站点包 S3Response 语法在collectstatic上出错

Django 自定义包含标签

postgresql - 如何使用 Node.js 中的 Lambda 函数从 Amazon RDS 获取数据?

sql - 如何在 PostgreSQL 9.5 中为 "int"数据类型设置大小限制

python - 异常值: 'User' object has no attribute 'update' thrown in DJANGO ORM

django - 如何在我的查询中使用反向关系?(django)

python - 在 django 上使用 Amazon S3 使用 ImageField 上传图像

python - Django 过滤 MySQL 警告