[Fixed]-Django: How to order a query set for a foreign key by a field of referencing class

1👍

There is always the option of default ordering, via the Meta class on each model. So:

class Part(models.Model):
    name = models.CharField(max_length=255)
    manufacturer = ...

    class Meta:
        ordering = ['name']  # or ['-name'] for descending

Now, everytime you get Part objects, they’ll be sorted by name unless an order_by is used in the query.

To come to your question, you can use this:

self.part_set.order_by('part__name')

but if you have already specified the ordering setting of Meta inside the Part class then you don’t have to write it that way. Instead write:

self.part_set.order_by('part')

and Django will order Part objects as per the Part Meta‘s ordering setting.

👤nik_m

Leave a comment