Search code examples
djangodjango-modelsmany-to-manydjango-filter

django queryset from other's queryset manytomany


What's the most efficient way to get all the records from a ManyToMany into a queryset?

To give an example, If I have a model named Events that has a ManyToMany to a model named Items and I have a queryset that contains Events. How do I get the queryset that contains all the Items that all the Events in the queryset point on?

If it was a single event, it would be: Events.items.all(). but this is a queryset so I can't do it.

Thanks


Solution

  • Items.filter(event_set__in=some_events_qs) will do it. This uses a lazily evaluated nested query - but see the performance considerations noted in the docs.

    This might return dupes if an Item belongs to more than one event in the initial queryset, I can never remember how that works. If so, .distinct() will clean it up but can also have a performance impact.