Home > Mobile >  combining two arrays in Django
combining two arrays in Django

Time:09-27

I'm working on a web that displays posts (like twitter). In Django views.py I wrote a code that makes two arrays and assigned the arrays to be used in the HTML template. views.py:

def arrays(request):
    allposts = posts.objects.all()
    m = ['empty', 'like', 'unlike', 'like', 'unlike']
    aa = [0, 1, 2, 3, 4]
    return render(request,  "network/index.html" ,{'allposts': allposts, 'm':m, 'aa':aa})

the (m) array represents whether each post is liked or not(each object in the array has the arrangement which is equal to the post id) while the (aa) represents the id of each post in the database

in index.html I want to show 'like' or 'unlike' for each post according to the arrangement in the array.

in index.html

{% for post in allposts %}
    <div>
    {% for object in aa %}
    {% if object == post.id %}
    <p>{{m.object}}</p>
    {% endif %}
    {% endfor %}

   
    </div>
    {%endfor %}
 

but the problem is that I can't match the aa array and the m array in the HTML template but I can display {{m.1}} instead of {{m.object}}. so how can I match those two arrays?

CodePudding user response:

Im not sure what you mean by 'match' and 'arrangement' here exactly. If i dont answer your question then please elaborate on what you are trying to accomplish.

the problem is that I can't match the aa array and the m array in the HTML template

This is vague but suggests you want to attach certain elements in m to certain elements in aa. I would suggest sending the data in a combined fashion like a dictionary

new_m = {a: m[a] for a in aa}

in index.html I want to show 'like' or 'unlike' for each post according to the arrangement in the array

This is also a bit vague but suggests you want to order m according to aa. Heres how you would do that:

m = [x for x,_ in sorted(zip(m, aa)]

Lastly, Im even more confused by this line in the template: {% if object == post.id %} because all it would do is only display your like, unlike, and other options on the first 5 posts.

CodePudding user response:

There are several ways to do it. I would filter your results with the list of IDs and sort it so it has the same order as your aa list. Then go with zip.

def arrays(request):
    aa = [0, 1, 2, 3, 4]
    filtered_posts = posts.objects.filter(id__in=aa).order_by("id")
    m = ['empty', 'like', 'unlike', 'like', 'unlike']
    posts_m_mapping = zip(filtered_posts, m)

    return render(request,  "network/index.html" ,{'posts_m_mapping': posts_m_mapping})

And in your template, just iterate over posts_m_mapping :

{% for post, sentiment in posts_m_mapping %}
   ...
{%endfor %}
  • Related