Django F表达式在datetime对象上(Django F expression on datetime objects)

编程入门 行业动态 更新时间:2024-10-26 10:31:55
Django F表达式在datetime对象上(Django F expression on datetime objects)

我的模型是:

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

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

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

我想找到所有的对象date2比date1一年。 如何根据date1和date2之间的差异找出对象?

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?

最满意答案

一般解决方案

您可以annotate日期差异,然后根据timedelta(days=365) (非常接近@Anonymous在其评论中建议的内容):

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


PostgreSQL特定解决方案:

如果您使用的是PostgreSQL ,则可以从此答案中获得另一个选项:

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

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))

更多推荐

本文发布于:2023-04-29 05:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   对象   Django   datetime   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!