SQLALCHEMY ORM - error when using variables both for column, value in WHERE

36 Views Asked by At

I'm little confusing on using orm.

I'm making GET user list function, and adding some conditions on it. I'm adding ORDER BY, LIMIT, and WHERE condition.

stmt = (
            select(
                MbrMember.member_seq,
                MbrMember.member_id,
                MbrMember.member_type_cd,
                MbrMember.member_status_cd,
                MbrMember.member_name,
                MbrMember.member_nick,
                MbrMember.member_memo,
                MbrMember.reg_dt,
                MbrMember.reg_member_seq,
                MbrMember.mod_dt,
                MbrMember.mod_member_seq,
            )
            .order_by(MbrMember.member_seq.asc())
            .limit(row_count)
        )
        if where_column and where_value:
            stmt = stmt.where(getattr(MbrMember, where_column[1:-1]) == where_value)

where_column is string so [1:-1] helps to get rid of commas

Code above is my intended code and it should be readed like this:

FROM mbr_member 
WHERE mbr_member.member_id = [email protected]
ORDER BY mbr_member.member_seq DESC 
LIMIT 5

(if where_column='member_id', where_value='[email protected]', row_count=5)

but it is readed like:

FROM mbr_member 
WHERE mbr_member.member_id = $1::VARCHAR 
ORDER BY mbr_member.member_seq DESC 
LIMIT $2::INTEGER

row_count in LIMIT and where_value in WHERE is not working well.

As the values are not written well, GET user list function returns like:

{
    "success": true,
    "message": null,
    "data": {
        "members_total_cnt": 0,
        "members": {}
    }
}

The function is returning empty list(even though there is the value in DB) but I can see mistakes in the log.

However, if I give up where_value and write code like below: stmt = stmt.where(getattr(MbrMember, where_column) == "[email protected]") It works fine. What is the problem and is it possible to solve? thanks

not using where_value in WHERE condition works fine

0

There are 0 best solutions below