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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T17:34:28+00:00 2026-06-06T17:34:28+00:00

I have two models like this: class ClassA(models.Model): ida = models.AutoField(primary_key=True) classb = models.ForeignKey(ClassB)

  • 0

I have two models like this:

class ClassA(models.Model):
    ida = models.AutoField(primary_key=True)
    classb = models.ForeignKey(ClassB)
    name = models.CharField(max_length=765)

class ClassB(models.Model):
    idb = models.AutoField(primary_key=True)
    name = models.CharField(max_length=765)

I want to show a list of all my ClassA objects grouped under a ClassB heading. This is the view I have:

def show_class_a_objects(request):
    class_b_objects = ClassB.objects.all().order_by('name')
    class_a_objects = ClassA.objects.all().order_by('name')
    return render_to_response('show_objects.html', {
        'class_a_objects': class_a_objects, 'class_a_objects': class_a_objects, 
    })

My show_objects.html file looks like this:

{% extends "base_show.html" %}
{% block content %}
</p>
<table>
<th align="left">Name</th>
{% for b in class_b_objects %}
    <tr>
    <td>{{b.name}}</td>
    </tr>
    {% for a in class_a_objects %}
        {% ifequal a.classb b %}
        <tr>
        <td><a href="{{ a.get_absolute_url }}">{{a.name}}</a></td>
        </tr>
        {% endifequal %}
    {% endfor %}
{% endfor %}
</table>
</br>
{% endblock %}

Is there a better way of doing this instead of using the two nested for loops?

  • 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-06-06T17:34:29+00:00Added an answer on June 6, 2026 at 5:34 pm
    def show_class_a_objects(request):
        class_b_objects = ClassB.objects.all().order_by('name')
        class_a_objects = ClassA.objects.all().order_by('name')
    

    You don’t need to query the ClassA objects like this to achieve the grouping you want. When you create a ForeignKey on your ClassA -> ClassB, your ClassB will contain a relation that will give you back all ClassA objects which have ClassB as a ForeignKey:

    view

    def show_class_a_objects(request):
        class_b_objects = ClassB.objects.all().order_by('name')
        return render_to_response('show_objects.html', {
            'class_b_objects': class_b_objects, 
        })
    

    template

    {% for b in class_b_objects %}
        <tr>
        <td>{{b.name}}</td>
        </tr>
        {% for a in b.classa_set.all %}
            <tr>
            <td><a href="{{ a.get_absolute_url }}">{{a.name}}</a></td>
            </tr>
        {% endfor %}
    {% endfor %}
    

    You still need a nested for loop, but you no longer have to loop over the entire range of every single other class and do comparisons to find the right ones.

    If you want a bit more control, you should move this into your view again and prebuild the dict:

    view

    def show_class_a_objects(request):
        class_b = ClassB.objects.all().order_by('name')
        class_b_objects = [(b, b.classa_set.all().order_by('name')) for b in class_b]
        return render_to_response('show_objects.html', {
            'class_b_objects': class_b_objects
        })
    

    template

    {% for b, a_list in class_b_objects %}
        <tr>
        <td>{{b.name}}</td>
        </tr>
        {% for a in a_list %}
            <tr>
            <td><a href="{{ a.get_absolute_url }}">{{a.name}}</a></td>
            </tr>
        {% endfor %}
    {% endfor %}
    

    Update: Reducing number of queries

    As per the comments, I wanted to address the issue of increasing the amount of database queries from your original 2, to the amount of 1 + num_of_classb_objects. This is because while the original ClassB query is 1, each of the b.classa_set.all() relation calls is another query to fetch the related ClassA instances.

    If you want to try and test an alternative, you can check out this blog post on efficient reverse lookups

    Example (adapted from link to your model names):

    qs = ClassB.objects.all()
    obj_dict = dict([(obj.id, obj) for obj in qs])
    objects = ClassA.objects.filter(classb__in=qs)
    relation_dict = {}
    for obj in objects:
        relation_dict.setdefault(obj.classb_id, []).append(obj)
    for id, related_items in relation_dict.items():
        obj_dict[id]._related_items = related_items
    

    Also, if you are running django >= 1.4, this functionality is supposedly official in the form of prefetch_related.

    I have not tested this, but I wanted to present it as something for you to look into if n+1 queries are not acceptable to you.

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

Sidebar

Related Questions

I have two models like so: class Visit(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=65535,
I have two models like this: class OptionsAndFeatures(models.Model): options = models.TextField(blank=True, null=True) entertainment =
I have two models like this: class Store(models.Model): name = models.CharField(max_length=255) class Order(models.Model): store
I have two models like this: class AA(models.Model): name = models.CharField() state = models.IngerField()
If I have two models like class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3,
I have two models: class Studio(models.Model): name = models.CharField(Studio, max_length=30, unique=True) class Film(models.Model): studio
I have two models like this: class A(models.Model): attachment = FileField(upload_to='a') class B(models.Model): attachment
So I have a few Django models that look like this: class City(models.Model): name
Let's say I have two models looking like this: class ProductType(models.Model): product_type = models.CharField(max_length=100)
I have two models like this: class Collar(models.Model): num_tags = models.BigIntegerField() class Dog(models.Model): num_legs

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.