How to make reverse relationship query with count in Django

Viewed 256

I have related models as defined below. I want to write a query to get all product that have product_options. I there a way I can achieve this or how to my attempted solution. I have pasted my solution below.

# Attempted Solution

Product.objects.filter(product_options__count__gt=0)

# Defined models

class Product(models.Model):
    name = models.CharField(max_length=200)


class ProductOption(models.Model):
    name = models.CharField(max_length=200)
    product = models.ForeignKey(
        Product,
        on_delete=models.PROTECT,
        related_name='product_options'
    )

2 Answers

You can easily do it by this query

Product.objects.filter(product_options__isnull=False)

It will send those product that doesn't have product options

Related