Skip to content

Instantly share code, notes, and snippets.

@afparsons
Last active August 24, 2023 08:06
Show Gist options
  • Save afparsons/6744568f345600e38f8e603a91f93101 to your computer and use it in GitHub Desktop.
Save afparsons/6744568f345600e38f8e603a91f93101 to your computer and use it in GitHub Desktop.
Django QuerySet PrettyPrint
# Enhanced Django QuerySet printing using PrettyPrinter
# Example usage: dropped into and employed within an IPython notebook.
# --- PRETTYPRINT -------------------------------------------------------------
# A PrettyPrinter object contains a _dispatch dictionary.
# This lookup table contains (key, value) pairs wherein the key corresponds to
# an object's __repr__ method, and the value is a special _pprint_<OBJECT>
# method. The PrettyPrint method pprint() queries the dictionary to call the
# appropriate object printer.
# --- _pprint_queryset() ------------------------------------------------------
# This printing method is nearly identical to _pprint_list().
# It is added to the _dispatch dictionary as the QuerySet's __repr__ function.
# --- _pprint_qs() ------------------------------------------------------------
# A wrapper method allowing for easy slicing, stream selection, and simple
# statistical report printing. This method is optional.
# --- Resources ---------------------------------------------------------------
# Derived from: Martjin Pieters: https://stackoverflow.com/a/40828239/4189676
# pprint source: https://github.com/python/cpython/blob/master/Lib/pprint.py
# Indent and modify as you see fit. Please comment with improvements.
import django
import pprint
def _pprint_queryset(printer, object, stream, indent, allowance, context, level) -> None:
stream.write('<QuerySet [\n ')
printer._format_items(object, stream, indent, allowance, context, level)
stream.write('\n]>')
pprint.PrettyPrinter._dispatch[django.db.models.query.QuerySet.__repr__] = _pprint_queryset
def pprint_qs(queryset: django.db.models.query.QuerySet, end: int=10, start: int=0, indent: int=3, stream=None, stats: bool=False) -> None:
pprint.pprint(queryset[start:end], indent=indent, stream=stream)
if stats:
count = queryset.count()
if count:
diff = abs(end - start)
showing = diff if diff < count else count
coverage = showing / count
percent_coverage = round(coverage * 100, 3)
report = f'showing: {showing} of {count} | {percent_coverage}%'
print('-' * 119)
print(report.rjust(119))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment