Assuming the following models, how exactly would one go about loading the shipment associated with the order via a subqueryload
, filtered by the status of is_refunded
?
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
class Shipment(db.Model):
id = db.Column(db.Integer, primary_key=True)
shipment = db.Column(MutableDict.as_mutable(JSONB))
is_refunded = db.Column(db.Boolean, server_default="false")
order_id = db.Column(db.Integer, db.ForeignKey('order.id'))
order = db.relationship('Order', backref='shipments')
I was hoping for something along the following lines, but this is not valid syntax:
orders = db.session.query(Order).options(
db.subqueryload(Order.shipments).filter(Shipment.is_refunded==False))
Some background:
- Order to Shipment is a One-to-Many relationship.
- As per business rules, although there maybe many shipments associated with an order, there can only be one "active" shipment. ie. all other shipments will have their
is_refunded
status set toTrue
- Thus, I am only interested in referring to the shipment that is "active" when iterating over all orders.
- The standard results returned by subqueryload load and return all shipments
- I am using the latest stable version of SQLAlchemy.
Please let me know if any clarifications are needed.
Thanks in advance.