hobbes3
hobbes3

Reputation: 30238

When is it a good idea to use the Django template tag "with"?

I understand that one of the biggest purpose of the with tag is to "cache a complex variable name" in a template.

But when is it a good idea to use it?

I'm assuming if I ever hit the database with count(), all(), filter(), or get() using the same template variable, then I should use with.

But what about for simple field lookups like user.username? In a particular template, I would be calling user.username many times.

Should I be using with for user.username or maybe even pass it a simple string from the view via a dictionary?

Upvotes: 0

Views: 65

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

The only reason to use with for user.username is if you don't like typing the long name each time. There's almost no overhead in that lookup, so there's no point trying to cache it.

Even forward foreignkey and one-to-one relations, like user.userprofile.name, are cached automatically by the ORM the first time you use them, so there's little point using with for those either.

Upvotes: 1

Related Questions