0

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.

3 Answers 3

1

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}}

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.