ApPeL
ApPeL

Reputation: 4911

django views only return if more than one result

I have a project and category model.

I am looking to only return results for the categories if they have 1 project or more...

this is what I have thus far, but it seems to return the wrong result.

def category():
    return { 'categories': Category.objects.filter(project=True).all().order_by('id')}

any ideas?

class Category(models.Model):
    title = models.CharField(max_length=30)
    slug  = models.SlugField(max_length=100, blank=True, null=True)

class Project(ImageModel):
    ...
    ...
    location = models.CharField(max_length=50, help_text='The city, town or area of the project.', null=True, blank=True)
    categories = models.ManyToManyField(Category)
    ...
    ...

Upvotes: 0

Views: 140

Answers (1)

Rich
Rich

Reputation: 7214

Category.project is a Manager.

You can use annotations. Something like:

Category.objects.annotate(projects=Count('project')).filter(projects__gt=1)

See the docs on annotations and aggregations

Upvotes: 1

Related Questions