Search this blog:

Words and works.

Ordering a Django Queryset

I was recently asked to change the sort ordering of a list for a Django-based project I worked on several months ago. Sounds easy, right? This simple task took much longer than it should have. The new ordering was to be based on a column (attribute) in a related table (model). According to the Django documentation for the latest version (svn trunk) the following syntax will accomplish the job:

qset = Entry.objects.order_by('category__name')

This project, however, used a somewhat older version of Django and the above did not work. Upgrading was not an option.

I eventually found a blog post wherein I learned that it is necessary to use the select_related function to tell Django's ORM to include the columns from related tables in the query. Once those related columns are present it becomes possible to order by a column in a related table using the following syntax:

qset = Entry.objects.select_related().order_by('blog_category.name')

This older syntax requires that you know the table name in the database. The new syntax is much cleaner. I hope this post saves someone some trouble.

Tags: django | Permalink

© 2010 Evenhouse Consulting, Inc.

A Django site.