python - SQLAlchemy, PostgreSQL and array_agg: How to select items from array_agg? -
I want to use in a subquery, then use the data collected by its array index in my main query, however, After trying many different ways, I am really in a disadvantage how it should be done; Can anyone explain why in the example given below, why did I get a series of values instead of the first class in the array?
I understand that the following, simple example array can be done without SELECTING [i], but it will explain the nature of the problem:
to sqlalchemy import from sqlalchemy .dialects.postgres Import import ARRAY prods = (session.query (Product.id.label ('id'), Func.array_agg (ProductCategory.id, type_ = ARRAY (integer)) Labels ('cats')). Outrojoined (ProductCafe, Productcake.product_id ==Products.id) .group_by (Product.id) .babber ()) # Confirm that there are categories in: [x] session.query (prods) for x) The LAN (x [1]) gt; 1] [4]: [[2428, [1633667, 1633665, 1633666]), (2462, [1162046, 1162043, 2543783, 1162045]), (2573, [1633697, 16336 9]), (25 9 8, [2546824, 922288, 92228]], (2645, [2544843, 338411]), (2660, [1633713, 1633714, 1633712, 1633711]), (2686, [2547480, 466995 , 466 9 6]), (2748, [2546706, 2879]), (2785, [467074, 467073, 2545804]), (2806, [2545326, 686295, 686298, 686297]]] "#" Try to query the range to get the array: [xx] x.x (prods.c.cats [0] .label ('first_cat')) in session.query "" (none), (none), (None), (none), (none), (none), (none), (none), (none), (none), (none), "" " / Code>
You are probably correcting all but getting the empty array first, in the last query you have in-person filtering ( len (x [1])> 1 ). You can print the query expression before executing it to make sure. You should probably add the base query to the section: cats_agg = func.array_agg (Product_Category.id, type_ = ARRAY (integer )). Label ('cats') prods = (session.query (Product.id.label ('id'), cats_agg. External (ProductCAG, ProductCA.Product_ID ==Products.id) .group_by (Product.Id) .Having ( Interesting.Rere_Lang (cats_agg, 1)> 1) .subquery ()) Then you will not need in-dragon filtering. < / html>
Comments
Post a Comment