I can not make a query that returns only the "YEARS" that have records!
Considering also that the field of my model is a FieldDate.
I can not make a query that returns only the "YEARS" that have records!
Considering also that the field of my model is a FieldDate.
In Django to return data grouped part of a date (day, month, year, etc.) it is necessary to use the extra. Example:
compras.extra(select={'month': "DATE_PART('year', data_compra)"}).values('month').annotate(Count('pk'))
In general, when I want to return something like this, I make a select with GROUP BY in the field I need.
Something like:
SELECT ano FROM registros GROUP BY ano
These features for building queries are often also available in django.
In Django we do not have group by , but thinking of these kind of cases we have aggregate and annotate
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
[<Publisher BaloneyPress>, <Publisher SalamiPress>, ...]
>>> pubs[0].num_books
73
[1] link