Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 58791
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T17:54:12+00:00 2026-05-10T17:54:12+00:00

This is a part algorithm-logic question (how to do it), part implementation question (how

  • 0

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.

In Python, it’s worth mentioning that the problem is somewhat related to how-do-i-use-pythons-itertoolsgroupby.

Suppose you’re given two Django Model-derived classes:

from django.db import models  class Car(models.Model):     mods = models.ManyToManyField(Representative) 

and

from django.db import models  class Mods(models.Model):    ... 

How does one get a list of Cars, grouped by Cars with a common set of Mods?

I.e. I want to get a 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’ve been 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, 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.

Cheers & thanks!

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T17:54:12+00:00Added an answer on May 10, 2026 at 5:54 pm

    Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.

    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 

    Now, about those queries:

    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]}] 

    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 dict for those, keyed by their ids – then, I believe, Bob is your proverbial father’s brother.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 86k
  • Answers 86k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You can use the System.Windows.Forms.Screen.AllScreens property to access a list… May 11, 2026 at 5:21 pm
  • Editorial Team
    Editorial Team added an answer The basic problem is you can't just serve a gzip… May 11, 2026 at 5:21 pm
  • Editorial Team
    Editorial Team added an answer I think there is a couple of issues with the… May 11, 2026 at 5:21 pm

Related Questions

Put simply a Soundex Algorithm changes a series of characters into a code. Characters
I'm trying to create a randomized maze in C++, but I can't start because
As discussed in similar questions here and here I want to protect my code
I'd like to store an additional column in a table as a 'sort value',

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.