How to print Django queryset in Tabular form in python3 manage.py shell

765 Views Asked by At

Is there a way or package to print Django queryset in Tabular form in python3 manage.py shell

The queryset prints like

this

But I want it to be printed like

this

1

There are 1 best solutions below

2
Alasdair On BEST ANSWER

Django doesn't have this feature, but it would be easy to create a function using tabulate

from tabulate import tabulate

def output_table(queryset, limit=50):
    headers = [x.name for x in queryset.model._meta.fields]
    rows = queryset.values_list(*headers)
    if limit is not None:
        rows = rows[:limit]
    print(tabulate(rows, headers))