views:

114

answers:

2

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_by(...)
+7  A: 

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.

Paolo Bergantino
This fails when datetime.today() is March 1st - last month was February, not January.If you don't need it be exact, this will work fine (30 days ago = last month) but if you do actually need to know what happened last month, there isn't an easy way to go about it in python (AFAIK).
Jough Dempsey
+3  A: 
items = Item.objects.filter(created_date__gte=aMonthAgo)

Where aMonthAgo would be calculated by datetime and timedelta.

John McCollum