Using "getters" on a template. Is it a bad practice?

I have a piece of code that works fine, but i think i’m not doing it in the “only good practices” way.
Here we go. (My questions are below the code)

My Models:
class Brand(models.Model):
    name = models.CharField(max_length=100)

class Product(models.Model):
    name = models.CharField(max_length=100, unique=True)
    brand = models.ForeignKey(Brand, related_name='product', on_delete=models.PROTECT)
    def get_total_weight_in_warehouse(self):
        return weight

My goal: to show all products (and their “in_warehouse_weight”) of a brand on brand_detail.html.

What I did:

class BrandDetailView(DetailView):
    model = Brand
    context_object_name = 'brand'

# brand_detail.html

{% for product in brand.product.all %}
    {{ product.get_total_weight_in_warehouse }}
{% endfor %}


This works perfectly, but:

  • Is it a bad practice to use product.get_total_weight_in_warehouse on a template?
  • Is it a bad practice to use brand.product.all on a template?
  • And if these are bad practices, how should i do it?


They’re not necessarily “bad” practices, but they may be suboptimal.

Generally speaking, you’re usually better off from a performance-perspective by ensuring all calculations and data preparations are done in the view and the results passed to the template through the context than having the template cause that code to be executed.

Now, whether it’s a “difference that makes a difference” is a question that can only be answered in the specific context of a particular situation. In many cases, “fast enough” is fast enough.

I tend not to worry about such things unless they’ve been shown to cause a real problem. (A page requiring .8 seconds instead of .2 seconds can generally be ignored. However, a page requiring 8 seconds instead of 2 is an issue usually worth looking at.)

1 Like

Thank you very much for the quick response!