Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render Django query set as column wise into html table?

Let's say my sql table looks like this..

products table

--------------------------------
| id | Model| Manufacturer     |
--------------------------------
| 1  | ABC  | Samsung          |
| 2  | XYZ  | LG               | 
| 3  | ZYX  | Sony             |
--------------------------------

in django view i fetched all records from this table and passed it to template..

def compare(request):
    product_ids = request.GET.get('product_ids')
    products = Product.objects.filter(id__in=product_ids)
    return render(request, 'compare.html', {'products': products})

as query_set result records comes like one after the other we can say it is following row wise but for this case in template i wanted to create an html table and the result should come like this ..

--------------------------------------------
|id           | 1       | 2        | 3     |
|Model        | ABC     | XYZ      | ZYX   |
|Manufacturer | Samsung | LG       | Sony  |
--------------------------------------------

By looking at above example you can see data is rendered as column wise.

so please suggest me a better method in Django by which i can achieve this and also please correct me if i'm wrong as i'm beginner in Django.

Thanks in advance

like image 298
Vishal Taj PM Avatar asked Jan 30 '23 03:01

Vishal Taj PM


2 Answers

Use values_list() and convert your queryset to list

products = list(Product.objects.filter(id__in=product_ids).values_list('id', 'Model', 'Manufacturer'))
# OUTPUT: [(1, 'ABC', 'Samsung'), (2, 'XYZ', 'LG'), (3, 'ZYX', 'Sony')]

Now transpose this 2d matrix using zip

t_products = list(zip(*products))
# OUTPUT: [(1, 2, 3), ('ABC', 'XYZ', 'ZYX'), ('Samsung', 'LG', 'Sony')]

finally you can loop over it in your template

<table>
  <tbody>
    {% for pl in t_products %}
    <tr>
      {% for l in pl%}
         <td>{{l}}</td>
      {% endfor %} 
    </tr>
    {% endfor %}
  </tbody>
</table>
like image 171
Satendra Avatar answered Jan 31 '23 19:01

Satendra


You can use pandas.DataFrame.transpose() i.e.,

import pandas as pd
from django_pandas.io import read_frame
df = read_frame(product)
table_html = df.transpose().to_html()

You just pass the table_html string to the template; no template logic needed here. There are several ways to convert a QuerySet to a DataFrame. Here I'm using the django-pandas package.

like image 35
pandichef Avatar answered Jan 31 '23 18:01

pandichef