Search code examples
djangomany-to-manydjango-queryset

Django queryset to filter objects with identical manytomany field


I've got a model like this.

class Component(models.Model):
     options = models.ManyToManyField('prices.Option')
     period = models.IntegerField()

I need to select all components with same period and same options as one component cmp. This queryset doesn't work.

similar_components = Component.objects.filter(period=cmp.period, options=cmp.options)

I can't find a way to make a queryset baset on this manytomany field options.


Solution

  • Many-to-many relationships

    from django.db.models import Q
    
    options = cmp.options.all()
    filter_kwargs = (Q(options=option) for option in options)
    similar_components = Component.objects.filter(period=cmp.period).filter(*filter_kwargs)