[Answered ]-Django โ€“ filter all products that have only empty variations

1๐Ÿ‘

โœ…

You can check if the sum of the quantities is zero, so:

from django.db.models import Sum


Product.objects.alias(
    stock_variations_count=Sum('variations__stock_quantity')
).filter(stock_variations_count=0)

or you can just exclude a Product that has any variant greater than zero:

from django.db.models import Sum


Product.objects.exclude(stock_variations__stock_quantity__gt=0)

the two are not entirely the same for Products with no variant.

or if you want to filter this out, you use:

from django.db.models import Sum


Product.objects.alias(
    stock_variations_count=Sum('variations__stock_quantity')
).filter(stock_variations_count__gt=0)

Leave a comment