[Sqlalchemy-tickets] Issue #3254: Join should be able to follow relationships implicitly (zzzeek/sq
Brought to you by:
zzzeek
|
From: nickretallack <iss...@bi...> - 2014-11-21 01:44:00
|
New issue 3254: Join should be able to follow relationships implicitly https://bitbucket.org/zzzeek/sqlalchemy/issue/3254/join-should-be-able-to-follow nickretallack: It's my opinion that this should work: ``` #!python from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, ForeignKey, Integer, String, ForeignKeyConstraint from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, relationship Model = declarative_base() class Parent(Model): __tablename__ = 'parent' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) class Child(Model): __tablename__ = 'child' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) parent_id = Column(Integer, nullable=False) parent = relationship('Parent', primaryjoin='foreign(Child.parent_id) == remote(Parent.id)') engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) if __name__ == "__main__": Model.metadata.create_all(engine) session = Session() # setup parent = Parent(name="fred") child = Child(name="bob", parent=parent) session.add_all([parent, child]) session.commit() # payoff print session.query(Parent).join(Child).all() ``` It works if parent_id has a ForeignKeyConstraint. It also works if I change it to ```print session.query(Parent).join(Child.parent).all()```. But I think it should work without either of these changes. It would be very helpful in an application I'm working on now, which mixes queries very dynamically. I suppose I could work around it by searching my models for relationships to follow manually, or adding foreign key constraints to the model that do not actually exist in the database. I just wish it worked without having to do these things. |