0
votes

For a QuerySet of blog entries, I want to create a DateQuerySet of the months in which those posts were made. The query is:

dates = Entry.published.all().dates('pub_date', 'month')

According to the docs

"month" returns a list of all distinct year/month values for the field.

If I have 4 entries with dates :

  • (2012, Feb, 3rd)
  • (2012, Feb, 2nd)
  • (2012, Jan, 24th)
  • (2011, Dec, 28th)

I expect to get 3 datetime objects returned; one for Dec, Jan, Feb, instead I get 4 returned, one for each of the original dates

Is this expected behaviour? I've tried adding distinct() to the query, but it still returns every date.


UPDATE

A simple way to fix this is make a Set from the DateQuerySet:

dates = Entry.published.all().dates('pub_date', 'month')
return set(dates)

This removes the duplicates datetime objects but I still don't understand why this is happening (or if I am misunderstanding how dates() works)

2
I am curious, what does dates = Entry.published.dates('pub_date', 'month') return?akonsu
It returns a DateQuerySet which is basically a list of datetime objects. It returns one for every entry in the original queryset, regardless of whether or not the occur in the same month of notTimmy O'Mahony
does it also return duplicate dates as does the version with the all() call?akonsu
are you using the default Manager?akonsu
No, but the published manager inherits from the defaults and simply filters out Entries from the futureTimmy O'Mahony

2 Answers

1
votes

Your symptoms sound exactly like a GROUP BY query with ordering.

You can print query.query to see if there's ordering being applied to a field that would be added to the SELECT, thus making all of those distinct as well.

Entry.published.dates('pub_date', 'month').order_by() 
0
votes

datetimes() instead of dates(), is a good idea in datetime-type objects situation.

My Environment:

  • win10 + python3.6.8
  • django2.2.12

FYI: