0

If you look at the piece of code below, you will understand exactly what I want. Enough even if I only get the number of cars that comply with this condition. Or it would be great if we could create a new loop from cars that comply with this condition.

{% for car in cars %}
    {% if car.color == 'white' %}
            create new for loop from white cars
            or
            give me the numbers of white cars
    {% endif %}
{% endfor %}
3
  • Can you share the view that is generating the cars context variable? Commented May 8, 2020 at 1:34
  • Edit and post your views.py Commented May 8, 2020 at 1:47
  • 1
    in view.py you should create data with white cars and send it to template. If you want more colors then in view.py you should group cars by color and send as list/dict these groups. Commented May 8, 2020 at 3:16

2 Answers 2

1

It is not possible to do it in a template. Modify your ORM query statement.

white_cars = Car.objects.filter(color='white')

And use it in your template with single loop.

{% for car in white_cars %}
    // Your code
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

this is very big data and very grouped so I can not filter from orm.
Why not? Filtering in database is better choice.
Because I need to filter according to the arguments in html and I don't know in advance what to filter in the rendered html.
1

You can use regroup template tag to group the list of cars by the color and then select the list of cars with white color to iterate over.

{% regroup cars by color as cars_grouped_by_color %}



{% for cars in cars_grouped_by_color %}
  {% if cars.grouper == 'white' %}
    {% for car in cars.list %}
      ...
    {% endfor %}
  {% endif %}
{% endfor %}

Refer regroup documentation for more details.

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.