0

Using Flask/sqlalchemy - say I have multiple tables related to each other. Classic example: orders - Lineitems - products. How would I go about properly query the tables if I wanted all orders with all line items and all products. Here is my attempt:

query = Orders.query
   .join(Lineitems, Orders.id==Lineitems.orders_id)
   .join(Products, Lineitems.product_id == Product.id)
   .all()

Models

class Orders(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     lineitems = db.relationship("Lineitems", backref="orders")

class Lineitems(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))
     product_id= db.Column(db.Integer, db.ForeignKey('products.id'))
     products = db.relationship("Products", backref='products', foreign_keys=[product_id])

class Products(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     name = db.Column(db.String, nullable=False)
 
Cliff Ribeiro
  • 77
  • 1
  • 1
  • 7
  • See https://stackoverflow.com/questions/6580835/how-to-do-a-join-in-sqlalchemy-session-query, https://stackoverflow.com/questions/48206047/how-to-return-all-the-columns-with-flask-sqlalchemy-query-join-from-two-tables – Ilja Everilä Apr 07 '21 at 18:45
  • tried it multiple ways. my method worked for what I was looking for it to do. Thanks! – Cliff Ribeiro Apr 07 '21 at 23:24

0 Answers0