I would like to build a SQLAlchemy command to get information from a database table. To do it I use this lines of code :
JavaScript
x
6
1
def new_rows(table, target):
2
3
command = select(table)
4
5
return command_execution(command)
6
Target is a dictionary and I would like that if a key is present in target, I add it after my select command. For example, if target is :
JavaScript
1
5
1
target = {
2
"limit": 20,
3
"order_by": "name"
4
}
5
then my command would become :
JavaScript
1
2
1
command = select(table).limit(20).order_by(table.c["name"])
2
Is there a way to do this in a clean way in Python ?
Advertisement
Answer
The cleanest route is probably something like:
JavaScript
1
7
1
command = select(table)
2
if (value := target.get('limit')):
3
command = command.limit(value)
4
if (value := target.get('order_by')):
5
command = command.order_by(value)
6
7
If you’re absolutely positive that everything in the table is a method that can be applied to a command and that they’re in the right order, you could write:
JavaScript
1
4
1
command = select(table)
2
for key, value in target.items():
3
command = getattr(command, key)(value)
4
but it’s really ugly, and you should only do it if you can’t enumerate your possible suffixes.