castiel castiel - 3 months ago 12
Python Question

how to get backref name in sqlalchemy?

class User(Base):
__tablename__ = 'users'

addresses = relationship('Address', order_by='Address.id', backref='user')


class Address(Base):
__tablename__ = 'addresses'

user_id = Column(Integer, ForeignKey('users.id'))


The above code shows a very common one-to-many configuration in SQLAlchemy.

How can I get the
backref
name which is 'user' in the
User
class from a instance of
Address
? How can I know that I have a attribute named 'addresses' in the
User
class which indicates that
User
has many addresses?

I can get all the column information from the
__table__.columns
attribute, but seems like these are stored there as well.

Answer

we're trying to encourage use of the inspect() api new in 0.8:

>>> from sqlalchemy import inspect
>>> inspect(User).attrs.keys()
['addresses', 'id']
>>> User.addresses.property.backref
'user'
Comments