[英]SQLAlchemy: Join to subquery with no from field
I have a table called product_model with its corresponding ProductModel SQLAlchemy model. 我有一个名为product_model的表及其相应的ProductModel SQLAlchemy模型。
I wish to join the product_model table to a select sub query which simply unnests two PostgreSQL arrays (product model ids, and quantity) and then join the product_model table to this data. 我希望将product_model表连接到一个select子查询,该查询只是取消两个PostgreSQL数组(产品模型ID和数量),然后将product_model表连接到此数据。 The data is taken from a simple cart (a python dict).
数据来自简单的购物车(python dict)。 I am using PostgreSQL for this use case, however if a better idea exists I will be more than happy to use an alternative.
我正在使用PostgreSQL用于此用例,但是如果存在更好的想法,我将非常乐意使用替代方案。
In SQL this would look as follows (this statement calculates the total mass of all products in the cart): 在SQL中,这将如下所示(此语句计算购物车中所有产品的总质量):
SELECT SUM(p.mass * c.quantity) FROM product_model AS p
INNER JOIN (
SELECT UNNEST(ARRAY[1]) AS model_id, UNNEST(ARRAY[2]) AS quantity
) AS c ON p.id = c.model_id
GROUP BY p.id;
I would like to model this SQL statement in SQLAlchemy. 我想在SQLAlchemy中建模这个SQL语句。 Is this possible?
这可能吗? I'm not sure how to join to a subquery which doesn't select from a table.
我不知道如何加入一个不从表中选择的子查询。 Or will I need to search for an alternative?
或者我需要寻找替代方案吗?
Not sure how good your solution is, but here's how to write your SQL query using SQLAlchemy: 不确定您的解决方案有多好,但是这里是如何使用SQLAlchemy编写SQL查询:
from sqlalchemy.dialects.postgresql import array
# First write the subquery. array() function is used for Pg ARRAY literals.
subq = db.session.query(
db.func.unnest(array([1])).label('model_id'),
db.func.unnest(array([2])).label('quantity')
).subquery()
# Now when you have the subquery, you can use it as if it were a Table object.
q = db.session.query(db.func.sum(ProductModel.mass * subq.c.quantity)).\
join(subq, ProductModel.id == subq.c.model_id).\
group_by(ProductModel.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.