Django different models' m2m relations fields comparsion related to same m2m model

I'm following this question to filter on M2M field: Django filter queryset __in for *every* item in list

I'm using .annotation approach.

My models:

class Options(models.Model):
    name = models.CharField(max_length=50)

class Product(models.Model):
    options = models.ManyToMany(Category)

class Item(models.Model):
    options = models.ManyToMany(Category)

I'm trying to filter Product instance to contain all categories as Item instance has:

items = Item.objects.all()
for item in items:
    item_options = [option.name for option in item.options.all()]
    queryset=models.Product.objects.filter(
                         status=Status.COMPLETED,
                         options__name__in=item_options
                         )\
                         .annotate(num_options=Count("options"))\
                         .filter(num_options=len(item_options))

It works in most cases except when Item doesn't contains any options. In this case I woul d like to match Product instance which also haven't any options but it fails returning no objects.

Back to Top