Django选择不同

时间:2010-09-13 07:51:41

标签: django django-orm

models.py

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Gender(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Post(models.Model):
    name = models.CharField(max_length=50)
    categories = models.ManyToManyField(Category)
    genders = models.ManyToManyField(Gender)

    def __unicode__(self):
        return self.name

view.py:

def index(request):
    posts = Post.objects.filter(genders=1)

    categories = Category.objects.filter(post__genders=1)
                                 .exclude(post=None).order_by('-sort')

如果3个帖子的性别等于1,为什么我会获得3次相同的类别?我只需要第1类时间我选择像“选择不同” - 我该怎么办?

1 个答案:

答案 0 :(得分:21)

您是否尝试将.distinct()附加到查询集?

categories = Category.objects.filter(post__genders=1).exclude(post=
      None).order_by('-sort').distinct()