Blessan Kurien Blessan Kurien - 21 days ago 5
Python Question

Python django custom query result in html

Just started to learn python django framework ,i am trying to display a custom query result in html page.

def index(request):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM polls_post")
context ={
'all_posts':cursor.fetchall()
}


In my html page

<ul>
{% for post in all_posts %}
<li>{{ post }}</li>
{% endfor %}
</ul>


But it displays the value as tuples ,so how can i get query result with table column name such as i can print the values like this way

<ul>
{% for post in all_posts %}
<li>{{ post.title }}</li>
<li>{{ post.name }}</li>
{% endfor %}
</ul>

Answer

You cannot - using cursor you need to repack data by yourself inside view and then pass the list of objects to the template.

Something like

posts = []

with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM polls_post")

    for obj in cursor.fetchall():
        posts.append({"title": obj[0], "name": obj[1]})
context = {'all_posts':cursor.fetchall()}

However I suppose that you rather want to use Django's ORM framework. Take a look at the Model reference then.

Comments