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...
精彩评论