- July 21, 2008
- choices ordering
- 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 for x in Object.DIRECTION_CHOICES].index(x.direction))
More like this
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 4 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago