Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Related objects in Django

I have 2 models Category and Item. An Item has a reference to a Category.

class Category(models.Model):
    name = models.CharField(max_length=32)

class Item(model.Models):
    name = models.CharField(max_length=32)
    category = models.ForeignKey(Category)
    sequence = models.IntegerField()

The sequence field is supposed to capture the sequence of the Item within a category.

My question is: What Meta Options do i need to set on category and/or item such that when i do:

category.item_set.all()

that I get the Items sorted by their sequence number.

PS: I am now aware of a meta option called ordering_with_respect_to .. but it is still unclear how it works, and also i have legacy data in the sequence columns. I am open to data migration, if the right approach requires that.

like image 746
arustgi Avatar asked May 23 '11 15:05

arustgi


1 Answers

What you're looking for is:

class Item(model.Models):
    name = models.CharField(max_length=32)
    category = models.ForeignKey(Category)
    sequence = models.IntegerField()

    class Meta:
        ordering = ['sequence',]

That will ensure that Items are always ordered by sequence.

like image 184
Chris Pratt Avatar answered Oct 04 '22 23:10

Chris Pratt