6

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.

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

Comments

3
category.item_set.all().order_by('sequence')

2 Comments

Is there a way to set a default ordering so that I don't have to manually sequence it each time ?
Thanks Uko. Would the order_with_respect_to that you have suggested, be on the Category model or the Item model?
2

Kinda late, and the previous answers don't solve my specific question, but they led me to an answer, so I'm gonna throw this in:

I need to sort my prefetch_related objects specifically for only one view, so changing the default ordering is no good (maybe a model_manager would do it, idk). But I found this in the docs.

I have the following models:

class Event(models.Model):
    foo = models.CharField(max_length=256)
    ....

class Session(models.Model):
    bar = models.CharField(max_length=256)
    event = models.ForeignKey(Event)
    start = models.DateTimeField()
    ....

    class Meta:
        ordering = ['start']

Now in a particular view, I want to see all the Events, but I want their Sessions in reverse order, i.e., ordering = ['-start']

So I'm doing this in the view's get_queryset():

from django.db.models import Prefetch
session_sort = Session.objects.all().order_by('-start')
prefetch = Prefetch('sessions', queryset=session_sort)
events = Event.objects.all().prefetch_related(prefetch)

Hope it helps somebody!

*BTW, this is just a simplified version, there are a bunch of filters and other prefetch_related parameters in my actual use case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.