I have models which describe a game. There are 61 provinces with 9
rooms in each province, for a total of 549 locations. There are
several hundred samurai, each assigned to a particular room id.

Province(name, id, exits)
Room(id, name, foreignkey('Province'))
Samurai(id, name, foreignkey('Room'))

I want to display a list of samurai (by id) for each province on the
admin/change_list.html.

I created a method in the Province model:

def samurai(self):
            r = self.room_set.filter(province = self.pk).all()
            output = []
            for i in r:
                output.extend(i.samurai())
            return unicode(output)

I use list_detail.object_list as the generic view and call the
province.samurai method from my template:

        {% for province in object_list %}
    <tr>
              <td>{{ province.name }} [{{ province.id }}] </td>
            <td>{{ province.exits }}</td>
                <td>{{ province.samurai }} </td>
    </tr>
        {% endfor %}

This is very slow, taking almost 4 seconds for 260 samurai.

I know that the reason this is slow is because I am hitting the
database so inefficiently. I have a for loop where each province is
iterating 9 times and I am iterating this loop 61times.

I'm new to databases and to django, so I'm trying to understand how I
can grab all the data in one query and then just use it. I think I
should do this from the view?

Can you give me a list of steps (in pseudo-code) for optimizing this
query?

eg:
1) Get all objects in province from the view
2) create a dictionary
3) and so on...

I just don't grok how the template, view, model method, and ORM fit
together to make an efficient query. :/

-Tim

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to