awwester
awwester

Reputation: 10162

Django get row count by date

I have been mulling over this for a while looking at many stackoverflow questions and going through aggregation docs I'm needing to get a dataset of PropertyImpressions grouped by date. Here is the PropertyImpression model:

#models.py
class PropertyImpression(models.Model):
    '''
    Impression data for Property Items
    '''
    property = models.ForeignKey(Property, db_index=True)
    imp_date = models.DateField(auto_now_add=True)

I have tried so many variations of the view code, but I'm posting this code because I consider to be the most logical, simple code, which according to documentation and examples should do what I'm trying to do.

#views.py
def admin_home(request):
    '''
    this is the home dashboard for admins, which currently just means staff.
    Other users that try to access this page will be redirected to login.
    '''
    prop_imps = PropertyImpression.objects.values('imp_date').annotate(count=Count('id'))

    return render(request, 'reportcontent/admin_home.html', {'prop_imps':prop_imps})

Then in the template when using the {{ prop_imps }} variable, it gives me a list of the PropertyImpressions, but are grouped by both imp_date and property. I need this to only group by imp_date, and by adding the .values('imp_date') according to values docs it would just be grouping by that field?

When leaving off the .annotate in the prop_imps variable, it gives me a list of all the imp_dates, which is really close, but when I group by the date field it for some reason groups by both imp_date and property.

Upvotes: 1

Views: 270

Answers (1)

pchiquet
pchiquet

Reputation: 3177

Maybe you have defined a default ordering in your PropertyImpression model?

In this case, you should add order_by() before annotate to reset it :

prop_imps = PropertyImpression.objects.values('imp_date').order_by() \
                                      .annotate(count=Count('id'))

It's explained in Django documentation here:

Fields that are mentioned in the order_by() part of a queryset (or which are used in the default ordering on a model) are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things.

Upvotes: 2

Related Questions