Skip to content
Advertisement

What is the best way to create a dynamic selection list from database column with Python and Flask WFForms?

Spent several hours today trying to get the unique values in my database into a dropdown selection with Flask WTForms.

The Database is MySQL, and I’m actually using SQLAlchemy for the majority of this app, but I’ve been unable to get unique values into the dropdown with SQLAlchemy (only seem to manage to get the string representaion in or the query itself)

other options use QuerySelectField, but this is from WTForms.ext which will be depreciated from WTForms3 so I’d rather avoid it.

The solution I have seems clunky and I feel there should be a better, more pythonic way. My current solution is with the mysql.connector

JavaScript

While this works and I can get a unique dropdown (the query itself isn’t unique, but this table is just a list of countries, no duplicates), I don’t feel like this is very scalable as my forms get more complex. Also the way in which I’ve setup the models, (Market, Competitor and then a lookup table), I need to map this back to a market ID and add to the lookup table (code for this isn’t shown here as I’m only concerned with the selection dropdown for now, but i thought the context would help understand the models:

JavaScript

Advertisement

Answer

this answer has most of the groundwork, with this I used the following to create the distinct list:

JavaScript

this gave:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement