class AllInManager(models.Manager): """ Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags') """ def from_related_ids(self,id_list, field): if len(id_list) == 1: mapper = { '%s__in' % field : id_list} query = self.model.objects.filter(**mapper) else: from django.db import connection cursor = connection.cursor() opts = self.model._meta field = opts.get_field(field) table = field.m2m_db_table() query = """ SELECT %(field)s FROM %(table)s WHERE %(field_reverse)s IN (%(id_list)s) GROUP BY %(field)s HAVING COUNT(%(field_reverse)s) = %%s """ % { 'field': field.m2m_column_name(), 'field_reverse': field.m2m_reverse_name(), 'table': table, 'id_list': ','.join(['%s'] * len(id_list))} params = [int(i) for i in id_list] + [len(id_list)] cursor.execute(query, params) erg_ids = cursor.fetchall() query = self.model.objects.filter(pk__in=[i[0] for i in erg_ids]) return query