views:

630

answers:

2

I have Django models that are lists of items and I want the items on each list to have a separate sort order. Maybe list 1 will sort line items by name, list 2 by date, and list 3 by priority.

The models looks more or less like this:

class ListItem(models.Model):
    priority = models.IntegerField(choices=PRIORITY_CHOICES)
    name = models.CharField(max_length=240)
    due_date = models.DateTimeField(null=True, blank=True)
    list = models.ForeignKey(List)

Right now I'm using this query in my view:

lists = List.objects.filter(user=request.user)
return render_to_response('showlists.html', {'lists': lists })

I've read examples that imply that I could do something like this:

lists = List.objects.filter(user=request.user).select_related().order_by("items.name")

Assuming that worked, it would give me the collection of lists with an identical sort order for each batch of items. How would I go about sorting each individual list's related items differently?

+2  A: 

If the lists are small, then you could do it in python, using sort and tagging

list = <...code to get sublist here ...>
list.sort(key=lambda x: x.due_date) #sort by due date, say

Otherwise kick off a query for each sub-list

Tom Leys
+1  A: 

The syntax for ordering across related models is the same double-underscore format as for filter, so you can do:

List.objects.filter(user=request.user).select_related().order_by("listitems__name")

You should just able to use the different fields in the same way in the order_by call.

Daniel Roseman
Thank you. Is there an easy way to do it differently for each list or will I have to break them apart and handle sorting one-by-one?
Jason Champion