'How to pass a Flask-SQLAlchemy Table as a parameter to my view?
I'm trying to write my own admin-backend. Selecting a database Table from a menu should call a view function with the selected Table as parameter. The list of Table names I got through:
def get_navbar_data():
# retrieve all tablenames from database
inspector = inspect(db.engine)
tables = inspector.get_table_names()
and is thus a mere list of strings. The selection itself takes place in an HTML template:
<div class="dropdown">
<button class="db-btn">Database
<i class="fa fa-caret-down"></i>
</button>
<div class="db-content">
{% for table in tables[1:] %}
<a href="{{ url_for('dashboard_database', table=table) }}">{{ table }}</a>
{% endfor %}
</div>
</div>
This calls a view in routes.py, where I need to query the selected table - but the passed tablename is just a string, not a database object:
@app.route('/dashboard_database/<table>')
def dashboard_database(table):
tables, filelist = get_navbar_data()
# get data for selected table
data = table.query.all()
return render_template(f'admin/db_{table}.html', tables=tables, filelist=filelist, data=data)
Running this code results in the following error:
File "/home/eos/Documenten/Python_Projects/blog/app/routes.py", line 187, in dashboard_database
data = table.query.all()
AttributeError: 'str' object has no attribute 'query'
How, then, should I retrieve the requested database Table object, so that I can query it? I'm using Flask-SQLAlchemy with sqlite3...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
