-1

I am using 5 - 6 custom template tags.

Each one of them is similar to the following:

@register.filter(name = 'time_left')
def time_left(obj):
    if not obj:
        return -1
    if not obj.has_offer_expired():
        return obj.time_left()
    return None

I have this in my models.py:

def has_offer_expired(self):
    return self.end_time <= timezone.now()

def time_left(self):
    return int((self.end_time - timezone.now()).total_seconds())

Whenever the template tag is used, {{ offer | time_left }}, will it cause a database query? Or, offer is passed to the template tag function and its attributes are used without causing any extra db query?

A detailed explanation of the working of template tags behind the scenes would be much appreciated!

Thank you.

Edit: Please add a reason before down voting the question!

2
  • 1
    Why would they cause a database query? If offer is already fetched, then no. If however offer contains attributes, etc. wity lazy loading, it will just work like any other query, and thus fetch related objects. Sep 15, 2018 at 16:48
  • offer is already fetched with all its attributes. Thanks! Sep 15, 2018 at 16:50

1 Answer 1

0

Depends on how you work around data in your template tags.

Basically when you load a row or more from database, you'll have everything about it. On the other hand if you need to access relations then you will send another query which you can also combine that query to the first one using prefetch methods.

Calls like calling a m2m field can cause a new query to the database but if you need the main attributes, then the same object on template will be passed and same data will be available without an extra query.

prefetch_related()

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.