SQLAlchemy: Getting a single object from joining multiple tables

前端 未结 3 685
说谎
说谎 2021-01-01 01:32

DB - SQLAlchemy setting

Consider a classic setting of two tables - user and api_key, represented by SQLAlchemy objects as:



        
3条回答
  •  滥情空心
    2021-01-01 02:13

    Instead of querying objects, query for list of fields instead, in which case SQLAlchemy returns instances of KeyedTuple, which offers KeyedTuple._asdict() method you can use to return arbitrary dictionary:

    def my_function(user_id):
        row =  database.db_session.query(User.name, ApiKey.api_key)\
            .join(ApiKey, User.vioozer_api_key==ApiKey.api_key)\
            .filter(User.user_id==user_id).first()
        return row._asdict()
    
    my_data = my_function('user_00000000000000000000000000000000')
    

    But for your particular query, you do not need even to join on ApiKey as the api_key field is present on the User table:

    row = database.db_session.query(User.name, User.api_key)\
        .filter(User.user_id==user_id).first()
    

提交回复
热议问题