Skip to content

Instantly share code, notes, and snippets.

@dooferlad
Last active July 31, 2019 14:45
Show Gist options
  • Save dooferlad/95c4bcc6fa4d2496464ff73f037a2cd2 to your computer and use it in GitHub Desktop.
Save dooferlad/95c4bcc6fa4d2496464ff73f037a2cd2 to your computer and use it in GitHub Desktop.
Very pretty print of Django objects
from django.db import models
def vpprint(item):
"""
Very pretty print of Django objects
:param item: Object to print
:return: None
"""
print(item.__class__.__name__)
_vpprint(item, [item.__class__.__name__], set())
def _vpprint(item, parents, visited):
todo = []
visited.add(item.__class__.__name__)
for name in dir(item):
if name[0] == "_" or name.isupper():
continue
try:
v = getattr(item, name)
if callable(v):
# Don't bother with callables. Properties have already been called so we get those!
continue
if (
name.endswith("_id")
and hasattr(item, name[:-3])
and isinstance(getattr(item, name[:-3]), models.Model)
):
# If this is the id used for a foreign key don't print it - we print the related
# object.
continue
if len(parents):
prefix = " " * len(parents) + "↳"
else:
prefix = ""
if isinstance(v, models.Model):
todo.append((name, v))
elif isinstance(v, models.QuerySet):
q = f"[... {len(v)} items ...]"
print(prefix, f"{name:>40} {q:<40} {type(v)}")
else:
print(prefix, f"{name:>40} {str(v):<40} {type(v)}")
except:
pass
for name, v in todo:
if v.__class__.__name__ in visited:
continue
print(" " * len(parents), f"{name} ({v.__class__.__name__})")
_vpprint(v, parents + [name], visited)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment