Batch Editing in Flask-Admin
Asked Answered
G

0

4

I'm using Flask-Admin and I want to be able to update many fields at once from the list view. It seemed like what I'm looking for is a custom action.

I was able to make it work, but I suspect not in the best way. I'm wondering if it could be done more "Flask"-ily.

What I do now, for example if I was updating all rows in table cars to have tires = 4:

  • A custom action in the CarView class collects the ids of the rows to be modified, a callback url from request.referrer, and the tablename cars, and returns render_template(mass_update_info.html) with these as parameters.
  • mass_update_info.html is an HTML form where the user specifies 1) the field they would like to change and 2) the value to change it to. On submit, the form makes a POST to a a certain view (do_mass_update) with this data (everything else is passed as hidden fields in this form).
  • do_mass_update uses the data sent to it to construct a SQL query string -- in its entirety, "UPDATE {} SET {}='{}' WHERE id IN ({})".format(table, column, value, ids) -- which is run via db.engine.execute().
  • The user is redirected to the callback url.

It bothers me that I don't seem to be using any of SQLAlchemy, but (from a newbie's perspective) it all seems to be based on the model objects e.g. User.query(...), while I only have access to the model/table name as a string. Can I get some kind of identifier from the model, pass that through, and do a lookup to retrieve the on the other side?

Geibel answered 2/7, 2015 at 14:36 Comment(1)
This sounds about right. I'd use dynamic query builder instead of string concatenation though. See here: docs.sqlalchemy.org/en/rel_1_0/orm/…Provenance

© 2022 - 2024 — McMap. All rights reserved.