Skip to content

Instantly share code, notes, and snippets.

@spookylukey
Last active January 7, 2020 12:17
Show Gist options
  • Save spookylukey/8d6779a144962e2b53c25e6320fdde90 to your computer and use it in GitHub Desktop.
Save spookylukey/8d6779a144962e2b53c25e6320fdde90 to your computer and use it in GitHub Desktop.
visidata glue code for Django models and attrs
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)
@spookylukey
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment