1
>>> 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)
4

1 回答 1

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
于 2013-10-09T21:47:04.410 回答