﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
6804	QuerySets should allow for ordering by intermediary tables	floguy	nobody	"Right now if one model is related to another model through a third model, ordering as one would expect is not possible to achieve.

Here is an illustration (both using patch #6095 and not):

{{{
class Group(models.Model):
    name = models.CharField(max_length=20)

    def __unicode__(self):
        return self.name

class Person(models.Model):
    name = models.CharField(max_length=20)
    groups = models.ManyToManyField(Group, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    priority = models.IntegerField()
}}}

This would be the output:

{{{
>>> from myapp.models import Group, Person, Membership
>>> g1 = Group.objects.create(name='beatles')
<Group: beatles>
>>> g2 = Group.objects.create(name='abc')
>>> p1 = Person.objects.create(name='John')
>>> p2 = Person.objects.create(name='Jane')
>>> m1 = Membership.objects.create(person = p1, group = g1, priority=1)
>>> m2 = Membership.objects.create(person = p2, group = g2, priority=2)
>>> p1.groups.order_by('membership__priority')
Traceback (most recent call last):
...
FieldError: Cannot order by many-valued field: 'membership__priority'
}}}

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."		closed	Uncategorized	queryset-refactor		fixed		floguy@…	Accepted	0	0	0	0	0	0
