0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.