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

  • Home
  • SEARCH
  • 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
  • 0 Views
  • 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 64k
  • Answers 64k
  • 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
  • added an answer You have to close that application first. There is no… May 11, 2026 at 10:40 am
  • added an answer AFAIK, the main windows you'd want to use are the… May 11, 2026 at 10:40 am
  • added an answer If you need spam emails to datamine with, then you're… May 11, 2026 at 10:40 am

Related Questions

This is a part algorithm-logic question (how to do it), part implementation question (how
This is a two part question. A dumb technical query and a broader query
I think this is a multi-part question, so bear with me. Currently all of
This is actually a two part question. First,does the HttpContext.Current correspond to the current
I am looking to set full trust for a single web part, is this
I have a property called IsSecureConnection that is part of my object's interface. This
I'm programmatically adding ToolStripButton items to a context menu. That part is easy. this.tsmiDelete.DropDownItems.Add(The
This one is a case of not doing your homework.:-) Apart from dynamic loading
This is a bit of a long shot, but if anyone can figure it
This is a difficult and open-ended question I know, but I thought I'd throw

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.