1👍
First of all: please don’t do the hack you proposed, it seems very error-prone and smelly.
Anyway the answer very much depends on what does do_something
actually do. If it is somehow accessing template context where you have stored the model instance then no, Django won’t hit database more than once if the model is already fetched from server – the data from db are stored in instance.__dict__
.
But if the do_something
logic does not work with the template context and instead has its own logic than yes – it will be called more once. You can use caching tools like https://pythonhosted.org/django-memoize/ but in your case caching will only work for that user case only if you call the function with the same arguments. Which is not the case – you are calling it with x,y,z…
You could make cached function that access the database if the database logic is same for x,y,z calls and than call this function from within the template tag.
0👍
You can also just cache in some way objects that your template tag is using when is first called, so next calls can re-use them. Template tags are getting context variable, you can add here your ‘cached’ objects as variable.