开发者

Django model filter, depending on exsisteing relation

开发者 https://www.devze.com 2023-01-15 02:02 出处:网络
How can I ONLY the categories where there is at least one \"Post\" related??, hope it makes sense!? **models.py**

How can I ONLY the categories where there is at least one "Post" related??, hope it makes sense!?

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

def __unicode开发者_C百科__(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( ??? )

How can I ONLY the categories where there is at least one "Post" related??, hope it makes sense!?


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


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)

Each foreignkey have a reverse relation to its parent model, so ypu must place a foreignkey to your Post model and post__isnull=False will return only categories that have a reverse relation to some posts...

0

精彩评论

暂无评论...
验证码 换一张
取 消