You can do this using the join of the request object, you do not need to specify this attribute directly. Thus, your model will look like this:
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.orm import sessionmaker, relation from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('sqlite:///') Session = sessionmaker(bind=engine) class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) addresses = relation("Address", backref="user") class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email = Column(String(50)) user_id = Column(Integer, ForeignKey("users.id")) Base.metadata.create_all(engine)
The request after the addresses with filtering the user name is as follows:
>>> session = Session() >>> session.add(Address(user=User(name='test'))) >>> session.query(Address).join(User).filter(User.name == 'test').first() <__main__.Address object at 0x02DB3730>
Change Since you can directly access a user from an address object, there is no need to directly refer to the attribute of the Address class:
>>> a = session.query(Address).join(User).filter(User.name == 'test').first() >>> a.user.name 'test'
schlamar
source share