Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.</p> <pre><code>import itertools cars = [ {'car': 'X2', 'mods': [1,2]}, {'car': 'Y2', 'mods': [2]}, {'car': 'W2', 'mods': [1]}, {'car': 'X1', 'mods': [1,2]}, {'car': 'W1', 'mods': [1]}, {'car': 'Y1', 'mods': [2]}, {'car': 'Z1', 'mods': [1,2,3]}, {'car': 'X3', 'mods': [1,2]}, ] cars.sort(key=lambda car: car['mods']) cars_by_common_mods = {} for k, g in itertools.groupby(cars, lambda car: car['mods']): cars_by_common_mods[frozenset(k)] = [car['car'] for car in g] print cars_by_common_mods </code></pre> <p>Now, about those queries:</p> <pre><code>import collections import itertools from operator import itemgetter from django.db import connection cursor = connection.cursor() 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]) # Here's one I prepared earlier, which emulates the sample data we've been working # with so far, but using the car id instead of the previous string. 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(cars.iteritems(), 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 # Which, for the sample data gives me (reformatted by hand for clarity) [{'cars': [3, 5], 'mods': [1]}, {'cars': [1, 4, 8], 'mods': [1, 2]}, {'cars': [7], 'mods': [1, 2, 3]}, {'cars': [2, 6], 'mods': [2]}] </code></pre> <p>Now that you've got your lists of car ids and mod ids, if you need the complete objects to work with, you could do a single query for each to get a complete list for each model and create a lookup <code>dict</code> for those, keyed by their ids - then, I believe, Bob is your proverbial father's brother.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload