Last active
January 7, 2020 12:17
-
-
Save spookylukey/8d6779a144962e2b53c25e6320fdde90 to your computer and use it in GitHub Desktop.
visidata glue code for Django models and attrs
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
import visidata | |
from django.db.models import QuerySet | |
def get_main_attrs(instance): | |
retval = [] | |
if hasattr(instance, '_meta'): | |
for field in instance._meta.get_fields(): | |
if not hasattr(field, 'get_attname'): | |
continue | |
if getattr(field, 'many_to_many', False): | |
continue | |
retval.append(field.get_attname()) | |
elif hasattr(instance, '__attrs_attrs__'): | |
for field in instance.__attrs_attrs__: | |
retval.append(field.name) | |
return retval | |
class AutoSheet(visidata.Sheet): | |
def reload(self): | |
self.rows = self.source | |
if len(self.rows) == 0: | |
self.columns = [] | |
else: | |
self.columns = visidata.AttrColumns(get_main_attrs(self.rows[0])) | |
def vd(objects): | |
""" | |
Wrapper around visidata.run with custom sheet types | |
""" | |
sheet = None | |
if isinstance(objects, QuerySet): | |
sheet = AutoSheet(objects.model.__name__, source=list(objects)) | |
elif isinstance(objects, list) and len(objects) > 0: | |
instance = objects[0] | |
if hasattr(instance, '_meta') or hasattr(instance, '__attrs_attrs__'): | |
sheet = AutoSheet(instance.__class__.__name__, source=objects) | |
if sheet is None: | |
sheet = visidata.load_pyobj('', objects) | |
return visidata.run(sheet) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better one here, with type support - https://gist.github.com/spookylukey/33afaa72edbb8d436fea45182aae49bc