This is part of the algorithm-logical question (how to do it), the question of implementation of the part (how to do it best!). I work with Django, so I decided to share this.
In Python, it's worth mentioning that the problem is somewhat related to how-do-i-use-pythons-itertoolsgroupby .
Suppose you are given two classes built by the Django Model:
from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative)
and
from django.db import models class Mods(models.Model): ...
How to get a list of cars grouped by cars with a common set of mods?
those. I want to get class likeso:
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' } }, ]
I was thinking of something like:
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
However, this does not work because (perhaps, among other reasons) groupby does not seem to be grouped together by mods. I think mod_list should be sorted to work with groupby. All that I can say, I'm sure that there will be something simple and elegant, which will be both enlightenment and lighting.
Greetings and thanks!