MrUzo
MrUzo

Reputation: 25

How to make .counts return 2 counts instead of 1

I have this line of code in my Django templates that returns counts of comments like 1, 2, 3...

<li class="list-inline-item">comms: {{ article.comments.count }}</li>

How do I make it return counts in twos for every comment? like 2, 4, 6...

I can provide further details if need be.

Thanks.

Upvotes: 0

Views: 37

Answers (1)

Alex
Alex

Reputation: 2474

Multiple solutions for this:

  1. Add a property on your Article model which will do the multiplication for you
class Article(models.Model):
    ...
    @property
    def comments_count_multiplied(self):
        return 2 * self.comments.count()

Now you can use this in your template:

<li class="list-inline-item">comms: {{ article.comments_count_multiplied }}</li>
  1. Register a custom template filter and use it in your template:
from django import template

register = template.Library()

@register.filter
def multiply_with_two(value):
    return 2 * value

And in your template:

<li class="list-inline-item">comms: {{ article.comments.count|multiply_with_two }}</li>

Upvotes: 2

Related Questions