Last active
January 24, 2025 12:11
-
-
Save afparsons/6744568f345600e38f8e603a91f93101 to your computer and use it in GitHub Desktop.
Django QuerySet PrettyPrint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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