Sort Relationships (ManyToMany) without duplicating records

2

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.

    
asked by AndreOlaya 29.04.2018 в 04:54
source

1 answer

0

Instead of using order_by , use the function values_list and then apply the distinct .

Example

Person.objects.all().values_list("membership__type", "group__name","id").distinct("id")

The values_list function will take out an array set for each Person and applying the distinct filter will filter the ones with the repeated id and will return the unique ones.

I hope it helps you.

    
answered by 03.05.2018 в 09:14