如何使用字符串变量作为表名进行sqlalchemy查询? [英] How to do a sqlalchemy query using a string variable as table name?

查看:400
本文介绍了如何使用字符串变量作为表名进行sqlalchemy查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不清楚,我事先表示歉意,英语不是我的母语. 如果我犯了太多错误,请随时告诉我:)

I apologize in advance if I am not clear, English is not my native language. Feel free to tell me if I make too many mistakes :)

我是使用flask_sqlalchemy的新手,花了数小时在互联网上寻找答案后感到沮丧.

I am a newbie in using flask_sqlalchemy and get frustrated after spending hours on Internet searching for an answer.

我想要做的是这样的查询:

What I want is doing a query like that one :

ModelName.query.filter_by(name='something').all()

但是我不想使用ModelName来做类似的事情:

But instead of using ModelName I want to do something like that :

model_list = ['Model1', 'Model2', 'Model3']
for model in model_list:
    some_var = model.query.filter_by(name='something').all()
    # do some stuff with the variable

错误是:

'str' object has no attribute 'query'

当尝试将db.session.add()与字符串变量一起使用时,我当然遇到同样的问题.

I have of course the same kind of problem when trying to use db.session.add() with a string variable.

我了解查询需要某种_BoundDeclarativeMeta对象而不是字符串,但是该如何从列表中获取该对象并将其传递给for循环?

I understand that the query requires some kind of _BoundDeclarativeMeta object instead of a string but then how to get that object from a list to pass it to a for loop ?

我尝试使用'db.metadata.tables [my_variable]',但是我得到了Table对象而不是_BoundDeclarativeMeta对象,并且它不能正常工作.

I tryed using 'db.metadata.tables[my_variable]' but I get a Table object instead of a _BoundDeclarativeMeta object and it doesn't work the same.

我设法使用

db.session.query(db.metadata.tables[my_variable])

代替

my_variable.query

但是我不能在'db.session.add()'中使用该方法(或者可能吗?)

but I can't use that method for the 'db.session.add()' (or is it possible ?)

有什么方法可以将字符串变量投射"到正确的sqlalchemy对象类型中?

Is there any way to 'cast' the string variable into the right type of sqlalchemy object ?

推荐答案

尝试一下:

mapping_str_to_object = {}
for model in BaseModel._decl_class_registry.values():
            if hasattr(model, '__tablename__'):
                mapping_str_to_object[model.__tablename__] = model

model_list = ['Model1', 'Model2', 'Model3']
for model in model_list:
    some_var = mapping_str_to_object[model].query.filter_by(name='something').all()  

这篇关于如何使用字符串变量作为表名进行sqlalchemy查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆