0

Why for my output.htm file, when I use django template "for loop" tags to retrieve data on {{ post.firstname }} and also {{ post.surname }}, it shows no result? Hope for help. Thanks in advance.

Ps: below code is only part of the work. This mean I didn't write out python libraries, full html for below code.

#views.py

class Student_list(View):
    def get(self, request):
        posts = Student.objects.all().values_list("firstname", "surname").union(Teacher.objects.all().values_list("firstname", "surname"))
        """raw sql => SELECT * FROM l2_OR_queries_student WHERE surname LIKE 'bald%' OR surname LIKE 'aus%' """
        return render(request, "l4_UNION_queries/output.htm", context = {"posts": posts})
<!--output.htm -->

    <table>
        <tr>
            <th>First Name</th>
            <th>Surname</th>
        </tr>

        {% for post in posts %}
        <tr>
            <td>{{ post.firstname }}</td>
            <td>{{ post.surname }}</td>
        </tr>
        {% endfor %}
    </table>
student.sqlite3

id  firstname   surname age classroom   teacher
4   shaina  austin  20  1   trellany
5   raquel  avery-parker    21  2   robin
6   lakisha baldwin 20  3   crystal


teacher.sqlite3
id  firstname   surname
9   trellany    abraham
10  robin   adkins
11  crystal allen
12  shaina  young

  • do you have data in get function? try to print `posts` data and check if it has data or not – Sabil Sep 19 '21 at 13:15
  • 2
    Does this answer your question? [Django values\_list vs values](https://stackoverflow.com/questions/37205793/django-values-list-vs-values) – Abdul Aziz Barkat Sep 19 '21 at 13:19
  • @Sabil when i print posts, here's the data: – TAN YONG SHENG Sep 19 '21 at 13:31
  • {% for firstname, surname in posts %}{{ firstname }}{{ surname }}{% endfor %} . I think I should write the html like this instead. But I just wonder why above method does not work (i.e. post.firstname, post.surname) – TAN YONG SHENG Sep 19 '21 at 13:34
  • @TANYONGSHENG well as you see when you print `posts` you get `` i.e. an iterable of _tuples_. If `var = ('crystal', 'allen')` and you write `var["firstname"]` do you think you will get what you want? Please read the linked question _carefully_. – Abdul Aziz Barkat Sep 19 '21 at 13:40

1 Answers1

0
 posts = Student.objects.all().values("firstname", "surname").union(Teacher.objects.all().values("firstname", "surname"))

You need to use values() instead of values_list() because values_list() returns the objects as a list. To access them by keys just use values().

lucutzu33
  • 3,470
  • 1
  • 10
  • 24
  • Thanks you all. I think I understand now. Since values_list() return list instead of dictionary object, thus I could not use key item of the dictionary object to access its value item. – TAN YONG SHENG Sep 19 '21 at 14:28