zogo
zogo

Reputation: 515

counting values using count function

i have the following template namely index.html.I am working in django framework.Now i have shown the value where the all speed of a car is more than 30km.I just posted here the part of the associated code which output the value,that is,the code is

{% for v in values %}
      {% if v.speed > 30 %}
        {{v.speed}}
      {% endif %}
{% endfor %}  

now i just want to count the v.speed values,how can i do that using python or django count function.You can edit my code in that section.

Thank You.

Upvotes: 0

Views: 64

Answers (3)

Maciej Gol
Maciej Gol

Reputation: 15854

Alternatively, since your QuerySet has been already evaluated, using the length filter would save you an additional query:

{% for v in values %}
  {% if v.speed > 30 %}
    {{v.speed}}
  {% endif %}
{% endfor %}

{{values|length}}

Documentation.

Upvotes: 0

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13362

Variable assignment is not allowed in django. So, your only alternative is do the counting in python itself & pass the corresponding data to the template.

Thus, you should do the following in python

speedy_values = [v for v in values if v.speed > 30]

And then, pass the speedy_values to your template

{% for v in speedy_values %}
      {{v.speed}}
{% endfor %}
{{ v|length }} number of cars have speed greater than 30.

Upvotes: 1

Bulkan
Bulkan

Reputation: 2596

If values is a Django QuerySet you can just use .count()

{% for v in values %}
  {% if v.speed > 30 %}
    {{v.speed}}
  {% endif %}
{% endfor %}

{{values.count}}

You can also use {{values|length}}

Upvotes: 1

Related Questions