Reputation: 2732
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.
Upvotes: 0
Views: 361
Reputation: 10687
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.
Upvotes: 2
Reputation: 33378
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.
Upvotes: 0