Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Last active January 2, 2016 11:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-kleshnin/8298500 to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/8298500 to your computer and use it in GitHub Desktop.
Pretty print MongoEngine document. See also https://github.com/MongoEngine/mongoengine/issues/544
class PPrintMixin:
def __str__(self):
return '<{}: id={!r}>'.format(type(self).__name__, self.id)
def __repr__(self):
attrs = []
for name in self._fields.keys():
value = getattr(self, name)
if isinstance(value, (Document, EmbeddedDocument)):
attrs.append('\n {} = {!s},'.format(name, value))
else:
attrs.append('\n {} = {!r},'.format(name, value))
return '<{}: {}\n>'.format(type(self).__name__, ''.join(attrs))
class MyModel(PprintMixin, Document):
...
print(MyModel.objects.get()) # short version
print(repr(MyModel.objects.get())) # full version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment