Django模型过滤器,取决于exsisteing关系

时间:2010-09-08 14:03:02

标签: django django-models

我怎么能只有至少有一个“帖子”相关的类别?希望它有意义!?

**models.py**
class Category(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)

    def __unicode__(self):
        return self.name

**view.py:**
def index(request):
    categories = category.objects.filter( ??? )

我怎么能只有至少有一个“帖子”相关的类别?希望它有意义!?

2 个答案:

答案 0 :(得分:0)

models.py

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

    def __unicode__(self):
        return self.name

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

    def __unicode__(self):
        return self.name

views.py

def index(request):
    categories = Category.objects.filter(post__isnull=False)

每个外键与其父模型具有反向关系,因此ypu必须将一个外键放置到Post模型中,而 post__isnull = False 将仅返回与某些帖子具有反向关系的类别...

答案 1 :(得分:0)

categories = Category.objects.exclude(post=None)