-->

How to render table from custom sql with django-ta

2019-06-28 02:20发布

问题:

I'm working with Django and django-tables2 to make a nice representation of sql queries in a web-interface. I have a legacy sql code which is very-very complicated to define it throught standard models.py.

The question is: how can i render a table from custom sql query using django-tables2?

回答1:

The docs on populating a table with data show how you can create a table with a list of dictionaries as the input data.

import django_tables2 as tables

data = [
    {"name": "Bradley"},
    {"name": "Stevie"},
]

class NameTable(tables.Table):
    name = tables.Column()

table = NameTable(data)

Assuming your custom sql query returns data in a similar format, you should be able to use the same approach.



回答2:

Well, i didn't get the conception of djt2 right. So i should've rendered it using the conditional operator. And now it works perfectly with django's Manager.raw() and returns nice tables.

{% load render_table from django_tables2%}
 <link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" />

            {% if result%}
        {%render_table result%}
            {%endif%}

`