QuerySets should allow for ordering by intermediary tables
|Reported by:||floguy||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
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:
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.
Change History (4)
comment:1 Changed 8 years ago by floguy
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset