Django: How to group records using the YEAR from a Fielddate field?

Asked

Viewed 716 times

-1

I’m not able to perform a query that returns only the "YEARS" that have records!

Considering also that the field of my model is a Fielddate.

  • 5

    Please elaborate further on your question, if possible by showing what your model is, where exactly you want to go, what you have already tried to do, etc. Although @Guilherme below has managed to give an excellent answer in the face of a lack of information, this lack of detail makes it very difficult to give a satisfactory answer. " Help us help you!" :)

  • Please put code examples and better contextualize the question.

3 answers

6


In Django to return grouped data from 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'))
  • Okay. That’s what I was trying to do Lucas... vlw!

2

In general, when I want to return something like this, I perform a select with GROUP BY in the field I need.

Something like:

SELECT ano FROM registros GROUP BY ano

These resources for building queries are usually also available on Jango.

  • I don’t have a way to test this at the moment, but give a read on agregation and Annotation on Django, I believe that annotate is what you’re looking for.

  • that’s right William! VLW. @Ucas showed an example.. and solved a lot.

0

In Django we don’t have group by, but thinking about these kind of cases we created the Aggregate and annotate[1]

>>> 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] https://docs.djangoproject.com/en/dev/topics/db/aggregation/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.