For days I have been trying to sort a series of queries by passing as parameter objects.order_by ("relation"). distinct () of type "ManyToMany" but always duplicates the query "x" the number of relations, being the Last the desired one.
class Person(models.Model):
name = models.CharField(max_length=200)
groups = models.ManyToManyField('Group', through='GroupMember', related_name='people')
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=200)
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
class GroupMember(models.Model):
person = models.ForeignKey(Person, related_name='membership')
group = models.ForeignKey(Group, related_name='membership')
type = models.CharField(max_length=100)
def __unicode__(self):
return "%s is in group %s (as %s)" % (self.person, self.group, self.type)
# Deseo ordear (Person) por el orden deseado en dos campos.
Person.objects.all().order_by("membership__type", "group__name").distinct("id")
Note that despite adding "distinct ()" you are duplicating the values of the query, my question is what is the reason and how to solve it. The database that I am using PostgreSQL. Thanks.