2010-09-13 77 views
6

models.pyDjango的選擇不同

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倍,如果有3個職位,其中性別等於1?我只需要類別1的時間我喜歡「選擇不同」的選擇 - 我該怎麼做?

回答

15

您是否嘗試將.distinct()附加到查詢集?

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

非常感謝! :D ...那麼容易;) – pkdkk 2010-09-13 10:53:26