Login

Ordering a queryset by _CHOICES

Author:
gkelly
Posted:
July 21, 2008
Language:
Python
Version:
.96
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.