Django extract only year from date time in request

I have a shopping table with a column data period. I would like to select all the purchases that I made this year. below is my code but it does not work!

import datetime
today = datetime.date.today()
year = Purchases.objects.filter(date__year = today.year)

I expect the year should be 2018 checked out from 2018-04-12

+4
source share
2 answers

You can use the function ExtractYear, here is an example:

from django.db.models.functions import ExtractYear

qs = Purchases.objects.annotate(year=ExtractYear('date')).filter(year = today.year)
+2
source

Upon request, we can get the year from the type model field DateFieldas fieldname__year(for comparison). If we have a field named "purchase_date" in our model, we can filter data for a specific year as follows:

MyModel.objects.filter(purchase_date__year=targetyear)

, . :

import datetime
today = datetime.date.today()
purchases = Purchases.objects.filter(datatime__year=today.year)
0

Source: https://habr.com/ru/post/1696291/


All Articles