P
P
pcdesign2015-01-23 18:29:04
Flask
pcdesign, 2015-01-23 18:29:04

Which dumper to use for Flask sqlalchemy?

rows = db.session.query(User, UserItem).join(UserItem).filter(User.id == 2).all()
print(rows)


If you just use print, then there will be something like this:
(<models.User object at 0x7fae4f7d09b0>, <models.UserItem object at 0x7fae4f7d0ac8>)


How to display this kind of structure on the screen when debugging?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ismailov, 2015-01-26
@pcdesign

You need to define the __repr__ method for the class with which you describe the entity:
An example from the documentation ( docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html):

from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     password = Column(String)
...
...     def __repr__(self):
...        return "<User(name='%s', fullname='%s', password='%s')>" % (
...                             self.name, self.fullname, self.password)

I will add here from the comments the solution of the universal repr for alchemy mapper classes, so that with formatting:
from sqlalchemy import inspect
...
def __repr__(self):
        mapper = inspect(self).mapper
        ent = []
        for col in mapper.column_attrs:
            ent.append("{0}={1}".format(col.key, getattr(self, col.key)))
        return "<{0}(".format(self.__class__.__name__) + ", ".join(ent) + ")>"

It should be taken into account that there will be no associations in the resulting string, because otherwise we can end up with an infinite recursion.
With this method, you can override the __repr__ method of Base so as not to duplicate it for each class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question