How to do a sqlalchemy query using a string variable as table name?
<p>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 :)</p>

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

<p>What I want is doing a query like that one :</p>

<pre><code>ModelName.query.filter_by(name='something').all()
</code></pre>

<p>But instead of using ModelName I want to do something like that :</p>

<pre><code>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
</code></pre>

<p>The error is :</p>

<pre><code>'str' object has no attribute 'query'
</code></pre>

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

<p>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 ?</p>

<p>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.</p>

<p>I manage to do a query using</p>

<pre><code>db.session.query(db.metadata.tables[my_variable])
</code></pre>

<p>instead of  </p>

<pre><code>my_variable.query
</code></pre>

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

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