Dickson Afful
Dickson Afful

Reputation: 838

How to make reverse relationship query with count in Django

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'
    )

Upvotes: 5

Views: 1409

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can work with a .annotate() [Django-doc] and then .filter(…) [Django-doc]:

from django.db.models import Count

Product.objects.annotate(
    noptions=Count('product_options')
).filter(
    noptions__gt=0
)

Since , you can also work with .alias(…) [Django-doc]:

from django.db.models import Count

Product.objects.alias(
    noptions=Count('product_options')
).filter(
    noptions__gt=0
)

Upvotes: 4

Shubham Agrawal
Shubham Agrawal

Reputation: 427

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

Upvotes: 3

Related Questions