2

I need to have a nested loop in my Django template, where the outer loop goes through a list of objects, and the inner loop goes through a list of those object id's, and I want to only do something for the id's on the inner list, it never executes however. I think it has something to do with the condition for the if statement, because if I replace it with a true statement it works but it doesn't work as it is now

(I have checked to see that the id's overlap)

{% for outer in outer_obj_list %}
     {% for inner_id in inner_id_list %}
         {% if outer.id == inner_id %}
             // do something
             console.log({{inner_id}});
             console.log({{outer.id}});
         {% endif %}
     {% endfor %}
{% endfor %}

2 Answers 2

1

Syntax seems correct. I would just verbosely output everything.

Perhaps it should be something like this:

{% for main_obj in main_obj_list %}
     main_obj: {{ main_obj }}

     {% for obj_id in obj_id_list %}
        obj_id: {{ obj_id}}
        main_obj: {{ main_obj.id}}

         {% if main_obj.id == obj_id %}
             // do something
             match: {{main_obj.id}} ==  {{obj_id}} ;

         {% endif %}
     {% endfor %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

2 Comments

Don't think that will work, Here's the structure of the object: obj = {id:34, name="x"}, the outer_obj_list is, for example, [obj, obj, obj, obj], and the inner_id_list is: [34, 45], where 34 and 45 are id's of some of two of the objects in the outer_obj_list
I see - I would double check that you are not comparing numbers and strings - otherwise your syntax is correct. I updated my response to suggest a debugging approach If you're not getting any values maybe there is no match. Also, Is this within JS? Why the console.log?
1

Brother I am also face this problem so my clever mind get some clever solution about this problem we can do that with JavaScript easily so we need to run it in JavaScript and then.

{% for outer in outer_obj_list %}
     {% for inner_id in inner_id_list %}
          if(outer.id == inner_id.id ){
           console.log({{inner_id.id}});
           console.log({{outer.id}});
           //And also if we reserve place in DOM then we can 
           //change the inner Html of them easily like.
           //demo = document.getElementById("demo");
           //demo.innerHTML = inner_Id.id or outer.id
          }
     {% endfor %}
{% endfor %}

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.