Rafa
Rafa

Reputation: 487

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!

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

Upvotes: 7

Views: 9255

Answers (2)

Ganesh Negi
Ganesh Negi

Reputation: 2029

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)

Upvotes: 6

Grigoriy Mikhalkin
Grigoriy Mikhalkin

Reputation: 5593

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)

Upvotes: 12

Related Questions