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 171571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T13:00:41+00:00 2026-05-11T13:00:41+00:00

Is there an easy way to fetch the ManyToMany objects from a query that

  • 0

Is there an easy way to fetch the ManyToMany objects from a query that returns more than one object? The way I am doing it now doesn’t feel as sexy as I would like it to. Here is how I am doing it now in my view:

contacts = Contact.objects.all() # Use Custom Manager Method to Fetch Each Contacts Phone Numbers contacts = PhoneNumber.objects.inject(contacts) 

My Models:

class PhoneNumber(models.Model):     number = models.CharField()     type = models.CharField()      # My Custom Manager     objects = PhoneNumberManager()  class Contact(models.Model):     name = models.CharField()     numbers = models.ManyToManyField(PhoneNumber, through='ContactPhoneNumbers')  class ContactPhoneNumbers(models.Model):     number = models.ForeignKey(PhoneNumber)     contact = models.ForeignKey(Contact)     ext = models.CharField() 

My Custom Manager:

class PhoneNumberManager(models.Manager):     def inject(self, contacts):         contact_ids = ','.join([str(item.id) for item in contacts])         cursor = connection.cursor()          cursor.execute('''             SELECT l.contact_id, l.ext, p.number, p.type             FROM svcontact_contactphonenumbers l, svcontact_phonenumber p             WHERE p.id = l.number_id AND l.contact_id IN(%s)             ''' % contact_ids)          result = {}         for row in cursor.fetchall():             id = str(row[0])             if not id in result:                 result[id] = []              result[id].append({                  'ext': row[1],                  'number': row[2],                  'type': row[3]             })          for contact in contacts:             id = str(contact.id)             if id in result:                 contact.phonenumbers = result[id]          return contacts 
  • 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-11T13:00:42+00:00Added an answer on May 11, 2026 at 1:00 pm

    There are a couple things you can do to find sexiness here 🙂

    Django does not have any OOTB way to inject the properties of the through table into your Contact instance. A M2M table with extra data is a SQL concept, so Django wouldn’t try to fight the relations, nor guess what should happen in the event of namespace collision, etc… . In fact, I’d go so far as to say that you probably do not want to inject arbitrary model properties onto your Contact object… if you find yourself needing to do that, then it’s probably a sign you should revise your model definition.

    Instead, Django provides convenient ways to access the relation seamlessly, both in queries and for data retrieval, all the while preserving the integrity of the entities. In this case, you’ll find that your Contact object offers a contactphonenumbers_set property that you can use to access the through data:

    >>> c = Contact.objects.get(id=1) >>> c.contactphonenumbers_set.all() # Would produce a list of ContactPhoneNumbers objects for that contact 

    This means, in your case, to iterate of all contact phone numbers (for example) you would:

    for contact in Contact.objects.all():     for phone in contact.contactphonenumbers_set.all():         print phone.number.number, phone.number.type, phone.ext 

    If you really, really, really want to do the injection for some reason, you’ll see you can do that using the 3-line code sample immediately above: just change the print statements into assignment statements.


    On a separate note, just for future reference, you could have written your inject function without SQL statements. In Django, the through table is itself a model, so you can query it directly:

    def inject(self, contacts):     contact_phone_numbers = ContactPhoneNumbers.objects.\                             filter(contact__in=contacts)     # And then do the result construction...      # - use contact_phone_number.number.phone to get the phone and ext     # - use contact_phone_number.contact to get the contact instance 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a quick easy way to write the results from the query below
Is there some easy way to fetch all associations of a big object graph
is there an easy way to solve the following problem. Let's say I fetch
Is there an easy way to produce MSDN-style documentation from the Visual Studio XML
Is there an easy way to dump an array returned from mysql_fetch_row into a
Is there an easy way to iterate over an associative array of this structure
Is there an easy way in C# to create Ordinals for a number? For
Is there an easy way to avoid dealing with text encoding problems?
Is there an easy way to tell if a ruby script is already running
Is there an easy way to set the zoom level for a windows form

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.