如何在order_by查询中删除重复的对象?

时间:2013-10-09 21:37:05

标签: django django-models

>>> a = group.objects.order_by('groupname')
>>> print a
[<group: beginner 593785332>, <group: beginner 903647323>, <group: blbrz 229225098>]

我不希望拥有类似goupname的对象,我希望每个对象都有不同的groupname

[<group: beginner 593785332>,  <group: blbrz 229225098>]

我该怎么办?

from django.db import models
class accounts(models.Model):
    twitterid = models.IntegerField()
    credit    = models.IntegerField()
    activate  = models.TextField()
    ban       = models.TextField(blank=True)
    others    = models.TextField()
    def __unicode__(self):
        return u'%s' % (self.twitterid)
    class Meta:
        ordering = ['twitterid']

class group(models.Model):
    groupname        =  models.TextField()
    accounts=models.ForeignKey(accounts)
    def __unicode__(self):
        return u'%s %s' % (self.groupname, self.accounts)

1 个答案:

答案 0 :(得分:2)

如果您的数据库后端是PostgreSQL,您可以使用查询集来执行此操作:

a = group.objects.order_by('groupname').distinct('groupname')

不幸的是你使用的是SQLite,所以你最好在python中使用它:

a = group.objects.order_by('groupname')
groupnames = set()
b = []
for item in a:
  if a.groupname not in groupnames:
    b.append(a)
    groupnames.add(a.groupname)
a = b