Django: getting the list of related records for a list of objects

Posted by Silver Light on Stack Overflow See other posts from Stack Overflow or by Silver Light
Published on 2010-03-28T11:19:59Z Indexed on 2010/03/28 11:23 UTC
Read the original article Hit count: 170

Filed under:
|

Hello!

I have two models related one-to many:

class Person(models.Model):
    name      = models.CharField(max_length=255);
    surname   = models.CharField(max_length=255);     
    age       = models.IntegerField(); 


class Dog(models.Model):
    name      = models.CharField(max_length=255);
    owner     = models.ForeignKey('Person');

I want to output a list of persons below each person a list of dogs he has. Here's how I can do it:

in view:

persons = Person.objects.all()[0:100];

in template:

{% for p in persons %}
    {{ p.name }} has dogs:<br />
    {% for d in persons.dog_set.all %}
        - {{ d.name }}<br />
    {% endfor %}
{% endfor %}

But if I do it like that, Django will execute 101 SQL queries which is very inefficient.

I tried to make a custom manager, which will get all the persons, then all the dogs and links them in python, but then I can't use paginator (my another question: http://stackoverflow.com/questions/2532475/django-paginator-raw-sql-query ) and it looks quite ugly.

Is there a more graceful way doing this?

© Stack Overflow or respective owner

Related posts about django

Related posts about foreign-keys