views:

22

answers:

2

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__(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!?

A: 

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...

FallenAngel
Ups- my bad -class Post(models.Model): name = models.CharField(max_length=50) categories = models.ManyToManyField(Category) def __unicode__(self): return self.name
pkdkk
A "post" can have more then one category related!
pkdkk
A: 
categories = Category.objects.exclude(post=None)
Daniel Roseman
I got this to work! Thanks...
pkdkk