Fabio
Fabio

Reputation: 1332

Django - How to filter using a ManyToManyField field?

Models:

class Product(models.Model):
    ...
    options = models.ManyToManyField(Option, blank=True)

class Option(models.Model):
    ...

class ProductVariant(models.Model):
    ...
    product = models.ForeignKey(Product, on_delete=models.CASCADE) # parent product
    option = models.ForeignKey(Option, on_delete=models.DO_NOTHING, null=True)

I need to find all the ProductVariants where the option doesn't belong to any options on the parent product Product.

I tried doing the following filtering:

ProductVariant.objects.exclude(option_id__in=[o.pk for o in F('product__options')])

But I got the following exception:

'F' object is not iterable

Upvotes: 1

Views: 57

Answers (1)

blhsing
blhsing

Reputation: 106543

Try filtering by Count instead:

ProductVariant.objects.annotate(product_count=Count('option__product')).filter(product_count=0)

Upvotes: 1

Related Questions