I have a table called product_model with its corresponding ProductModel SQLAlchemy model.
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. The data is taken from a simple cart (a 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.
In SQL this would look as follows (this statement calculates the total mass of all products in the cart):
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. 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?