Reputation: 838
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
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 django-3.2, 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
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