Login

Ordering a queryset by _CHOICES

Author:
gkelly
Posted:
July 21, 2008
Language:
Python
Version:
.96
Tags:
choices ordering
Score:
0 (after 0 ratings)

I recently needed to sort a list of objects by cardinal direction clock-wise. Since this is different than alphabetical, and I didn't want to use a dictionary to map to integers, here is what I came up with.

There may be a cleaner way to do this by overriding some object methods, but I just thought I'd put this out there anyway.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#
# Example models
#
class Object(models.Model):
  DIRECTION_CHOICES = ('N','E','S','W')
  # define other fields here

class ObjectPhoto(models.Model):
  the_object = models.ForeignKey(Object)
  direction = models.CharField(choices=[(x,x) for x in DIRECTION_CHOICES], max_length=1)

# Then, in views.py, do something like this
  photo_list = list(object.objectphoto_set.all())
  photo_list.sort(key=lambda x: list(Object.DIRECTION_CHOICES).index(x.direction))
# photo_list is now sorted by direction, in the order specified in DIRECTION_CHOICES

# Note: if using tuples in the choices list, the lambda function will have to 
# change to use the correct tuple value. For example, if it was like this:
DIRECTION_CHOICES = [ ('N','North'),('E','East'),('S','South'),('W','West') ]
photo_list.sort(key=lambda x: [x[0] for x in Object.DIRECTION_CHOICES].index(x.direction))

More like this

Comments

Please login first before commenting.