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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T04:54:36+00:00 2026-05-18T04:54:36+00:00

I’m using a ManyToManyField with a ‘through’ class and this results in a lot

  • 0

I’m using a ManyToManyField with a ‘through’ class and this results in a lot of queries when fetching a list of things. I’m wondering if there’s a more efficient way.

For example here are some simplified classes describing Books and their several authors, which goes through a Role class (to define roles like “Editor”, “Illustrator”, etc):

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    @property
    def full_name(self):
        return ' '.join([self.first_name, self.last_name,])

class Role(models.Model):
    name = models.CharField(max_length=50)
    person = models.ForeignKey(Person)
    book = models.ForeignKey(Book)

class Book(models.Model):
    title = models.CharField(max_length=255)
    authors = models.ManyToManyField(Person, through='Role')

    @property
    def authors_names(self):
        names = []
        for role in self.role_set.all():
            person_name = role.person.full_name
            if role.name:
                person_name += ' (%s)' % (role.name,)
            names.append(person_name)
        return ', '.join(names)

If I call Book.authors_names() then I can get a string something like this:

John Doe (Editor), Fred Bloggs, Billy Bob (Illustrator)

It works fine but it does one query to get the Roles for the book, and then another query for every Person. If I’m displaying a list of Books, this adds up to a lot of queries.

Is there a way to do this more efficiently, in a single query per Book, with a join? Or is the only way to use something like batch-select?

(For bonus points… my coding of authors_names() looks a bit clunky – is there a way to make it more elegantly Python-esque?)

  • 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. Editorial Team
    Editorial Team
    2026-05-18T04:54:37+00:00Added an answer on May 18, 2026 at 4:54 am

    This is a pattern I come across often in Django. It’s really easy to create properties such as your author_name, and they work great when you display one book, but the number of queries explodes when you want to use the property for many books on a page.

    Firstly, you can use select_related to prevent the lookup for every person

      for role in self.role_set.all().select_related(depth=1):
            person_name = role.person.full_name
            if role.name:
                person_name += ' (%s)' % (role.name,)
            names.append(person_name)
        return ', '.join(names)
    

    However, this doesn’t solve the problem of looking up the roles for every book.

    If you are displaying a list of books, you can look up all the roles for your books in one query, then cache them.

    >>> books = Book.objects.filter(**your_kwargs)
    >>> roles = Role.objects.filter(book_in=books).select_related(depth=1)
    >>> roles_by_book = defaultdict(list)
    >>> for role in roles:
    ...    roles_by_book[role.book].append(books)    
    

    You can then access a book’s roles through the roles_by_dict dictionary.

    >>> for book in books:
    ...    book_roles = roles_by_book[book]
    

    You will have to rethink your author_name property to use caching like this.


    I’ll shoot for the bonus points as well.

    Add a method to role to render the full name and role name.

    class Role(models.Model):
        ...
        @property
        def name_and_role(self):
            out = self.person.full_name
            if self.name:
                out += ' (%s)' % role.name
            return out
    

    The author_names collapses to a one liner similar to Paulo’s suggestion

    @property
    def authors_names(self):
       return ', '.join([role.name_and_role for role in self.role_set.all() ])
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I am reading a book about Javascript and jQuery and using one of the
this is what i have right now Drawing an RSS feed into the php,
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am doing a simple coin flipping experiment for class that involves flipping a

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.