I saw the following implementation using sqlalchemy. It is a method that only makes the difference between narrowing down from the passed user list or narrowing down from the entire table. (Other conditions are exactly the same) I thought that it would be better to make it common when considering the correction, so I investigated the solution.
def get_specified_age_users_from_user_list(user_name_list={}, age):
"""
Get users of a specific age among the specified users from the User table
"""
users = session.query(User).\
filter(users.age==age).\
filter(users.name.in_(user_name_list)).\
all()
return users
def get_specified_age_users(age):
"""
Get users of a specific age from the User table
"""
users = session.query(User).\
filter(users.age==age).\
all()
return users
Pass the condition in tuple
format to the ʻand_` method.
from sqlalchemy import and_
def get_specified_age_users(user_name_list={}, age):
filters = []
#Add condition only if arguments are passed
if user_name_list:
filters.append(User.name.in_(user_name_list))
# and_The argument of is tuple because it needs to be tuple
users = session.query(User).\
filter(and_(*filters)).\
all()
return users
#SQL to be executed
##If specified
SELECT omitted
FROM users
WHERE users.name IN (%s)
##If not specified
SELECT omitted
FROM users
Recommended Posts