Django Extract Only Year from Date Time in Queryset
I Have a Purchases Table with a Column Datatime. I Would Like to Select All Purchases I Have Done in the Current Year. Bellow Is My Code but Is Not Working!...
I have a purchases table with a column datatime. I would like to select all purchases I have done in the current year. bellow is my code but is not working!
import datetime
today = datetime.date.today()
year = Purchases.objects.filter(date__year = today.year)
I expect the year should be 2018 extracted from 2018-04-12
2 Answers
You can use ExtractYear function, here is example:
from django.db.models.functions import ExtractYear
qs = Purchases.objects.annotate(year=ExtractYear('date')).filter(year = today.year)
While querying, we can get year from model field of type DateField as fieldname__year (for comparision). If we have a field named 'purchase_date' in our model, we can filter data for a particular year as:
MyModel.objects.filter(purchase_date__year=targetyear)
In your case, if the column name is datatime. You can get the purchases done in current year as:
import datetime
today = datetime.date.today()
purchases = Purchases.objects.filter(datatime__year=today.year)