Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: get subset of a model with at least one related model

class Category(models.Model):
    # fields

class Product(models.Model):
     category = models.ForeignKey(Category)
     # fields

Assuming that not all the categories have at least a product,

how i can get all the categories that have at least one product associated?

Is there a way to do this with Django querysets?

like image 408
apelliciari Avatar asked May 18 '13 14:05

apelliciari


1 Answers

You should be able to filter on the category. You want to find the Category's where the product isn't null right?:

Category.objects.filter(product_set__isnull=False).distinct()
like image 163
joneshf Avatar answered Sep 18 '22 23:09

joneshf