日期时间对象上的Django F表达式 [英] Django F expression on datetime objects

查看:49
本文介绍了日期时间对象上的Django F表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型是:

  class Test():
date1 = models.DateTimeField()
date2 = models.DateTimeField()

我可以找出 date2的对象大于 date1 ,使用以下查询:

  Test.obejcts.filter(date2__gt = F('date1'))

想要找到所有 date2 大于 date1 一年的对象。

如何我可以根据 date1 date2 之间的差异找出对象吗?

解决方案

常规解决方案:



您可以批注日期差异,然后对照 timedelta(days = 365)进行检查(与@Anonymous在其评论中建议的内容非常接近):

  Test.objects.annotate(
duration = F('date2')-F('date1')
) .filter(duration__gt = timedelta(天= 365))



PostgreSQL特定解决方案:



如果您使用的是 PostgreSQL ,则还有一个从此答案



<$ p来自django.db.models的$ p> 导入F,Func

Test.objects.annotate(
持续时间= Func(F('date2'),F( 'date1'),function ='age')
).filter(duration__gt = timedelta(days = 365))


My model is:

class Test():
   date1 = models.DateTimeField()
   date2 = models.DateTimeField()

I can find out objects who's date2 is greater than date1, using the following query:

Test.obejcts.filter(date2__gt=F('date1'))

I would like to find all the objects who's date2 is greater than date1 by one year.
How can I find out objects based on difference between date1 and date2?

解决方案

General Solution:

You can annotate the date difference and then check this against the timedelta(days=365) (pretty close to what @Anonymous suggests in his comment):

Test.objects.annotate(
    duration=F('date2') - F('date1')
).filter(duration__gt=timedelta(days=365))


PostgreSQL Specific Solution:

If you are using PostgreSQL, there is another option derived from this answer:

from django.db.models import F, Func

Test.objects.annotate(
    duration = Func(F('date2'), F('date1'), function='age')
).filter(duration__gt=timedelta(days=365))

这篇关于日期时间对象上的Django F表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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