订单关系(ManyToMany)没有重复记录django

时间:2018-04-29 17:41:30

标签: django python-3.x postgresql

有几天我一直试图通过传递参数objects.order_by(“relation”)。distinct()类型为“ManyToMany”来排序一系列查询,但总是复制查询“x”关系数,最后一个是期望的。

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)

# Create three people:
self.joe = Person.objects.create(name='Joe')

# And three groups:
self.jocks = Group.objects.create(name='Jocks')
self.nerds = Group.objects.create(name='Nerds')

GroupMember.objects.create(person=self.joe, group=self.jocks, type="admin")
GroupMember.objects.create(person=self.joe, group=self.nerds, type="owner")
GroupMember.objects.create(person=self.joe, group=self.nerds, type="member")

# Not work, recieve multiple queries duplicates.
# (alphabetical order)
# We need order_by GroupMember().type. "admin, member, owner,... "
Person.objects.all()\
             .order_by("membership__type")\
             .distinct("id")

请注意,虽然添加“distinct()”会复制查询的值,但我的问题是原因是什么以及如何解决它。我正在使用PostgreSQL的数据库。谢谢。

0 个答案:

没有答案