Getting all items less than a month old

后端 未结 3 2062
北海茫月
北海茫月 2021-02-18 13:05

Is there a way to get all objects with a date less than a month ago in django.

Something like:

items = Item.objects.filter(less than a month old).order_b         


        
3条回答
  •  心在旅途
    2021-02-18 13:33

    What is your definition of a "month"? 30 days? 31 days? Past that, this should do it:

    from datetime import datetime, timedelta
    last_month = datetime.today() - timedelta(days=30)
    items = Item.objects.filter(my_date__gte=last_month).order_by(...)
    

    Takes advantange of the gte field lookup.

提交回复
热议问题