Nested subquery with an inner join in Flask and Python
- Get link
- X
- Other Apps
Nested subquery with an inner join in Flask and Python
Let's say we have three tables in our database, orders
, customers
, and products
. We want to retrieve all the orders made by customers who live in the state of California and contain products with a price greater than $100. Here's how we can do it using a nested subquery with an inner join:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db' db = SQLAlchemy(app) class Order(db.Model): id = db.Column(db.Integer, primary_key=True) customer_id = db.Column(db.Integer, db.ForeignKey('customer.id')) product_id = db.Column(db.Integer, db.ForeignKey('product.id')) amount = db.Column(db.Float) class Customer(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) state = db.Column(db.String(2)) orders = db.relationship('Order', backref='customer', lazy=True) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) price = db.Column(db.Float) orders = db.relationship('Order', backref='product', lazy=True) @app.route('/orders/california-expensive') def get_expensive_orders_from_california(): subquery = db.session.query(Product.id).filter(Product.price > 100).subquery() orders = db.session.query(Order).join(Customer).join(subquery, subquery.c.id == Order.product_id).filter(Customer.state == 'CA').all()
return jsonify([order.amount for order in orders])
Order
, Customer
, and Product
models using SQLAlchemy. Then, in the get_expensive_orders_from_california
route, we use a nested subquery to filter products by price:Order
table to retrieve all orders that contain these products:We also use the join()
method to perform inner joins between the Order
, Customer
, and Product
tables. Finally, we use the filter()
method to filter customers by the state of California and the all()
method to retrieve all the matching orders, and return their amounts as a JSON response.
Note that we use the subquery.c.id
syntax to refer to the id
column of the subquery, and we use the ==
operator to match the product_id
column in the Order
table with the subquery result.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments
Post a Comment