Without an intermediary model (through="Membership"), it could happen like this:

>>> Person.objects.filter(id=1).order_by('membership__priority')

The idea is that there are some cases where you're absolutely certain that one side of the many-to-many relationship will resolve to a single record (in this case, p1). In those cases, ordering should be possible on the property in the intermediary table. It will become more of a common use case if/when #6095's functionality is added.

Attachments (1)

This does special case checking to see if it's a RelatedObject and if so, doesn't raise a JoinError. This causes one test to break, and that's because I don't understand the implications of the change that was made. Maybe this hack can be expanded upon to get a real solution. (Using patch #6095)

Change History (4)

By the way, I'm looking into implementing this (I'm thinking django.db.models.sql.query.setup_joins), but setup_joins looks like a crazy function and it might take quite a while to wrap my head around it.

This does special case checking to see if it's a RelatedObject and if so, doesn't raise a JoinError. This causes one test to break, and that's because I don't understand the implications of the change that was made. Maybe this hack can be expanded upon to get a real solution. (Using patch #6095)

This isn't the right solution because it's disguising the problem. Ordering across a random one-to-many relation does not, in general, make sense because it's multi-valued and your change removes the error detection for that case.

What is needed is for the query construction code to be able to know for certain that there won't be multiple values returned. This has nothing to do with the presence or absence of the intermediate model (ordering on a many-to-many relation isn't possible because it returns multiple-values). Instead, the intermediate model in this case needs a unique_together designator so the query code can tell that when person and group are specified, there will only be a single Membership instance.

So this ticket is really about adding support for respecting unique_together on models, which we can certainly add.