Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango/Python - Grouping objects by common set from a many-to-many relationships
    text
    copied!<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p> <p>Suppose you're given two Django Model-derived classes:</p> <pre><code>from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative) </code></pre> <p>and</p> <pre><code>from django.db import models class Mods(models.Model): ... </code></pre> <p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p> <p>I.e. I want to get a class likeso:</p> <pre><code>Cars_by_common_mods = [ { mods: { 'a' }, cars: { 'W1', 'W2' } }, { mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, }, { mods: { 'b' }, cars: { 'Y1', 'Y2' } }, { mods: { 'a', 'b', 'c' }, cars: { 'Z1' } }, ] </code></pre> <p>I've been thinking of something like:</p> <pre><code>def cars_by_common_mods(): cars = Cars.objects.all() mod_list = [] for car in cars: mod_list.append( { 'car': car, 'mods': list(car.mods.all()) } ret = [] for key, mods_group in groupby(list(mods), lambda x: set(x.mods)): ret.append(mods_group) return ret </code></pre> <p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p> <p><em>Cheers &amp; thanks!</em></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