Django: How to group records using the YEAR from a FieldDate field? [closed]

-1

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.

    
asked by anonymous 13.12.2013 / 15:29

3 answers

6

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'))
    
13.12.2013 / 15:53
2

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.

    
13.12.2013 / 15:34
0

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

    
19.01.2014 / 02:32