views:

142

answers:

2

I can't post image because I'm new so here's a link of what I want.

So, I have the model on the left and I want the view on the right.
As of now, I'm looping over every thread I'm interested in. Template code:

{% for thread in threadlist %}
{% for post in thread.postlist %}
...

Model code:

class Thread (models.Model):
...    
def postlist(self):
    posts = list(self.post_set.all())
    return [posts.pop(0)] + posts[-2:]

There must be a way to do this with less queries by joining columns or something. I'm pretty new to Python/Django and I don't really know how to do this.

A: 

Looking at the documentation you should be using post_set.all(). I'm pretty sure that the queries are joined by django behind the scenes, and that its lazy. Meaning it won't be loaded until its needed.

From the documentation:

QuerySets are lazy -- the act of creating a QuerySet doesn't involve any database activity. You can stack filters together all day long, and Django won't actually run the query until the QuerySet is evaluated.

MrHus
I'm doing a query for each thread, that's 10+ queries per page. I want only 1 loop instead of having 2 nested ones."QuerySets are lazy" means they're only executed when necessary and here every one of them is. My actual solution is not optimal.
knarf
+2  A: 

You can use select_related . This will make the query follow joins so you end up with one larger query, instead of many smaller ones.

The docs are pretty thorough.

Arthur Debert