Question: Django Meta ordering in related query


Django Meta ordering in related query

Answers 1
Added at 2016-12-30 22:12

How do you set a default order for Django queries that works on related managers?

You can set a default order with Meta.ordering:

class Subject(Model):
    title = TextField()

class Course(Model):
    subject = ForeignKey(Subject)

    class Meta:
        ordering = ['id']

This will set the order when you run Course.objects.all(). But when you run subject.course_set.all(), the courses can be out of order.

Ideally, a solution would involve no changes to the vast existing codebase that queries the db.

Note: The database is Postgresql

nr: #1 dodano: 2016-12-30 23:12

As far as i know, there is a hack
You can make a manager method like

class SomeManagerSet(models.QuerySet):
    def ordered(self):
        return self.order_by("id")

And activate it in model via

objects = SomeManagerSet.as_manager()

And then use in related query like subject.course_set.ordered()

Source Show
◀ Wstecz