Django F expression on datetime objects

前端 未结 2 1813
萌比男神i
萌比男神i 2020-12-09 21:52

My model is:

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

I can find out objects who\'s date2

2条回答
  •  一个人的身影
    2020-12-09 22:25

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

提交回复
热议问题