Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django select distinct

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')

Why do I get the same category 3 times if there are 3 posts where gender is equal to 1?? I only need the category 1 time i my select like "select distinct" - how can I do so??

like image 256
pkdkk Avatar asked Sep 13 '10 07:09

pkdkk


1 Answers

Did you try attaching a .distinct() to the queryset?

categories = Category.objects.filter(post__genders=1).exclude(post=
      None).order_by('-sort').distinct()
like image 134
Manoj Govindan Avatar answered Oct 16 '22 22:10

Manoj Govindan