Reputation: 51
I want to filter my datetime field with 1 month after from today without consider year.
class Contract(models.Model):
title = models.CharField(max_length=200, null=True)
date = models.DateField()
Example filter between: From: Today Day and Month: 01-05 (%m-%d) To: One Month Later: 02-05 (%m-%d)
Here is my code:
today = datetime.date.today()
foremonth = today + relativedelta(months=1)
return_list=[]
s = Contract.objects.filter(active=True).order_by('date__month', 'date__day')
for i in s:
k = i.date.strftime("%m-%d")
if k > today.strftime("%m-%d") and k < foremonth.strftime("%m-%d"):
return_list.append(i)
return return_list
How can I do with django query
Upvotes: 1
Views: 933
Reputation: 2212
What you could do is use the Django database functions as described here, Django annotations and combine them with Q
to create the query.
today = datetime.date.today()
foremonth = today + relativedelta(months=1)
start_day = today.day
start_month = today.month
end_day = foremonth.day
end_month = foremonth.month
# Create the query
query = Q(d__gte=start_day, m=start_month) | Q(d__lte=end_day, m=end_month)
# Annotate your objects with day and month and filter results
Contract.objects.annotate(d=ExtractDay('date'), m=ExtractMonth('date')).filter(query)
Upvotes: 1