I am using SQLAlchemy with FastAPI to build an API. So my current problem is, querying the data from the database. I have multiple tables e.g. Table Header, Table Foo and Table Bar.
class Header(Base):
idno = Column(NUMBER, primary_key=True)
id_db = Column(NUMBER, primary_key=True)
authorization = Column(NUMBER)
class Foo(Base):
idno = Column(NUMBER, primary_key=True)
id_db = Column(NUMBER, primary_key=True)
idno_header = Column(NUMBER, Foreign_key(Header.idno))
id_db_header = Column(NUMBER, Foreign_key(Header.id_db))
nr = Column(NUMBER)
header = relationship('Header')
class Bar(Base):
idno = Column(NUMBER, primary_key=True)
id_db = Column(NUMBER, primary_key=True)
idno_foo = Column(NUMBER, Foreign_key(Bar.idno)
id_db_foo = Column(NUMBER, Foreign_key(Bar.id_db)
data = Column(NUMBER)
foo = relationship('Foo')
The result should contain all data from the tables. I tried to solve this with the joinedload() method but could not achieve any results.
I tried something like this:
query = db.query(Header).join(Foo).join(Bar).options(joinedload(Foo), joinedload(Bar)).filter(Bar.data == 2)
I tried replacing joinedload() with contains_eager() but could not achieve any results too.
How should i write my query to get the results ?
Thanks for any help :)
ForeignKeyseparately. Looking at this question and its answer, you should define it using__table_args__andForeignKeyConstraintto get the joins working in SQLAlchemy. I would ask why all your tables have composite primary keys, do you need it for some reason? In general they can be a pain to work with. - M.O.query = db.query(Header).join(Foo).join(Bar).options(contains_eager(Foo), contains_eager(Bar)).filter(Bar.data == 2)I get an error message ` sqlalchemy.exc.ArgumentError: mapper option expects string key or list of attributes` - Christian Haag