Eli
Eli

Reputation: 5620

Django: calling DB queries from a template

I've got a Django site that has a sidebar with a variety of different boxes that could go in it depending on the page. For example, "Most recent comments" or "Latest tweets" or "Featured story." These boxes all require database queries to run.

I could simply add a most_recent_comments and whatever other variable are needed to the View for each page. But this feels brittle. I'd like to be able to move and change boxes just by editing the templates.

So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?

So what I think I want is some kind of custom tag where I could just say {% most_recent_comments_box %} and it would be smart enough to load whatever variables it needs from the database and then call a little template file. Is this the right approach? How do I accomplish that?

Upvotes: 3

Views: 4610

Answers (2)

lmz
lmz

Reputation: 1580

So my other thought was I could add all the variables that all the boxes might need to every page with a Context Processor, but is the ORM smart enough to only run the queries for pages that actually use those variables? Or is it going to hit the database even if I have no boxes on a page?

Yes, the ORM will be smart enough to do that. Django QuerySets are lazy: https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy

Upvotes: 1

Ismail Badawi
Ismail Badawi

Reputation: 37207

This is the use case for custom template tags. Read this article (written by one of the people behind Django).

One addition to Django since that article was written is the inclusion tag shortcut, which implements the "call a little template file" approach you mention.

Upvotes: 5

Related Questions