52010

How to do a proper groupby query in django

Question:

I have a table that holds multiple tracking id's in it. What I'm trying to do is group all tracking id's and get a count for them.

This is what the SQL query would look like:

SELECT tracking_id, COUNT( * ) FROM tracking GROUP BY tracking_id

I think I've found the correct method of doing this in django however I'm missing something and am currently getting the error Exception Value: 'dict' object has no attribute 'tracking_id'

Here's what my view looks like:

def stats(request): users = Tracking.objects.values('tracking_id').annotate(dcount=Count('tracking_id')) stats = [] for user in users: stats.append((user.tracking_id, user.dcount)) return render_to_response('tracking/stats.html', { 'stats': stats, })

Any help would be appreciated!

Answer1:

How about (partially inspired by @second's answer):

users = Tracking.objects.values( 'tracking_id' ).annotate(dcount=Count('tracking_id'))

and then

for user in users: stats.append((user[ 'tracking_id' ], user[ 'dcount' ]))

?

Answer2:

for times like this, I would recommend trying out your code in a shell

./manage.py shell opens a python shell with your project code in the system path

>>> from myapp.models import Tracking >>> from django.db.models import Count >>> Tracking.objects.values('tracking_id').annotate(dcount=Count('tracking_id')) [{'tracking_id': 53, 'dcount': 12}, {'tracking_id': 1, 'dcount': 32}, ...]

this lets you see the format of the returned data and get you on your way

alternatively, you can add a pdb (python debugger) statement in your view code, (assuming runserver is serving your code), and load the page. when the pdb statement is reached, your server will stop and drop you into a debugger shell, right in the context of your view

def view(request): [...] import pdb; pdb.set_trace # or even better, pip install ipdb and use instead return "foo"

Recommend

  • LibGDX GwtApplication Exception (TypeError) in HTML Deployment
  • how to save ouput of perf (Linux tool) to a file?
  • Fastest ways to get a directory Size and Size on disk
  • AnalyticsReceiver in Google Analytics Tracking
  • Custom variables on product details page in Magento
  • How to use both ga.js and analytics.js?
  • Other than Linq to SQL does anything else consume INotifyPropertyChanging?
  • Automatically associate new Sonar project with custom quality profile and quality gate
  • Set matplotlib plot axis to be the dataframe column name
  • Grails calculated field in SQL
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • CSS Linear-gradient formatting issue accross different browsers
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • HTML download movie download link
  • How to add date and time under each post in guestbook in google app engine
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Cassandra Data Model
  • JSON with duplicate key names losing information when parsed
  • Symfony2: How to get request parameter
  • Convert array of 8 bytes to signed long in C++
  • Return words with double consecutive letters
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • log4net write single file for each call to log.info
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Getting error when using KSoap library to consume .NET web services
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Understanding cpu registers
  • How do I configure my settings file to work with unit tests?
  • Getting Messege Twice Using IMvxMessenger
  • Is it possible to post an object from jquery to bottle.py?
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Python/Django TangoWithDjango Models and Databases
  • How to load view controller without button in storyboard?