How to take the names of the Django model table (queryset) columns into a list, template or other variable?

Question:

Good day!

I have a table model in Django model.
With named field column names.

I’m going to post this model to a table in a template.
But I have 8 .. 9 columns.

I would like to not specify the names of the table columns in the header manually.

And so that it is filled from the list, as is most often the case in the body of the table.
How it is possible to pull out to take from model or request in the list of a name of columns of fields?

header from queryset ("verbose_name") or model ?

template

<table>
<tr>{% for item in header %}<th>{{ item }}</th>{% endfor %}</tr>
{% for row in rows %}
<tr>{% for cell in row %}<td>{{ cell }}</td>{% endfor %}</tr>
{% endfor %}
</table>

Model

class Model_1(models.Model):
    name1 = models.ForeignKey(Model_2, on_delete=models.CASCADE, verbose_name="Name_0")
    name2 = models.ForeignKey(Model_3, on_delete=models.CASCADE, verbose_name="Name1")
    date3 = models.DateField(verbose_name="Name2")
Asked By: Cristensen

||

Answers:

You can use the model._meta.get_fields() method to get all the fields of a model, and then use the verbose_name attribute of each field to create the list of column names for the table header. Here is an example of how to do this in your view:

header = [field.verbose_name for field in Model_1._meta.get_fields()]

Then you can pass the header variable to the template context and use it to display the column names in the table header.

You can achieve this from a queryset as well. You can use the values() method on the queryset to return a list of dictionaries containing the column names as keys and their values. Then, you can extract the keys (column names) from the first dictionary in the list to use as the header in your template.

# Get column names from queryset. 
header = list(queryset.values().first().keys())
# Get rows from queryset  
rows = list(queryset.values())
Answered By: psky
<div class="container">
    <table class="table">
        <thead>
            <tr>
            {% for item in headers %}
                <th>{{ item }}</th>
            {% endfor %}
            </tr>
        </thead>
        {% for row in rows %}
        <tr>
            {% for cell in row %}
                <td>
                    {{ cell }}
                </td>
            {% endfor %}
        </tr>
        {% endfor %}
    </table>
</div>
Answered By: Cristensen