Sort Related Objects in Django

I have 2 models Category and Item. The item has a link 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 should capture the sequence of the element within the category.

My question is: What metadata parameters do I need to set for the category and / or element, for example, when I do:

 category.item_set.all() 

that I get items sorted by their serial number.

PS: Now I know a meta parameter called ordering_with_respect_to .., but it’s still unclear how this works, and also I have outdated data in the sequence columns. I am open to data transfer if this requires the right approach.

+4
source share
3 answers

What are you looking for:

 class Item(model.Models): name = models.CharField(max_length=32) category = models.ForeignKey(Category) sequence = models.IntegerField() class Meta: ordering = ['sequence',] 

This ensures that Item always ordered by sequence .

+6
source
 category.item_set.all().order_by('sequence') 
+3
source

Late, and the previous answers do not solve my specific question, but they led me to the answer, so I'm going to throw this at:

I need to sort prefetch_related objects for only one view, so changing the order by default is not suitable (maybe model_manager will do this, 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 specific view I want to see all Event s, but I want their Session in reverse order, i.e. ordering = ['-start']

So, I do this in the 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 this helps someone!

* BTW, This is just a simplified version, in my actual use there are many filters and other prefetch_related parameters.

0
source

All Articles