Search code examples
pythonsqlalchemypython-typing

Keep Object Definition with Multi Column Select


How can I keep object definition with select, that has more object defined and keep variable from becoming "Any" type? Is it even possible?

I came up with this:

DB = DatabaseModel() 

stmt = select(Item, Package).join(Package, Item.Package_id1 == Package.Package_id)
exec = DB.session.execute(stmt).all() # Sequence[Row[Tuple[Item, Package]]]

for row in exec:
    row #Row[Tuple[Item, Package]] 

    Item_object : Item = row[0]   
    Package_object : Package = row[1]  

This way I just define a value as Object, so I can keep the mapping. But is there a better (correct) way to do this? Without a need to create new variables?


Solution

  • So, I was able to come up with answer. I was not able to unpacked it, because this command:

    exec = DB.session.execute(stmt).all() 
    # Returned type: Sequence[Row[Tuple[Item, Package]]]
    

    And so in for loop I cant unpack typeof(Row) as I would typeof(tuple).

    So correct way to unpack values would be this:

    DB = DatabaseModel() 
    
    stmt = select(Item, Package).join(Package, Item.Package_id1 == Package.Package_id)
    exec = DB.session.execute(stmt).tuples().all() # Sequence[Tuple[Item, Package]]]
    
    for _item, _package in exec:
        .....
    

    Adding .touples() in execute statements removes Row definition and only returns tuples.