djangodjango-modelsdjango-shell

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


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


Solution

  • 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))