cursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2')
cars = collections.defaultdict(list)
for row in cursor.fetchall():
    cars[row[0]].append(row[1])
cars = {(1): [1, 2], (2): [2], (3): [1], (4): [1, 2], (5): [1], (6): [2], (
    7): [1, 2, 3], (8): [1, 2]}
sorted_cars = sorted(iter(cars.items()), key=itemgetter(1))
cars_by_common_mods = []
for k, g in itertools.groupby(sorted_cars, key=itemgetter(1)):
    cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)})
print(cars_by_common_mods)
[{'cars': [3, 5], 'mods': [1]}, {'cars': [1, 4, 8], 'mods': [1, 2]}, {
    'cars': [7], 'mods': [1, 2, 3]}, {'cars': [2, 6], 'mods': [2]}]
Django/Python - Grouping objects by common set from a many-to-many relationships