librelist archives

« back to archive

QuerySelectField question

QuerySelectField question

Charles Griebel
2012-06-07 @ 16:00
[tl;dr - sorry]
I am a flask newbie using the sqlalchemy extension and I have a
question about foreign keys and forms and the use of
wtf.QuerySelectField. When I go to collect the form data from a POST
the wtf.QuerySelectField is an object so when I persist a new record
in the db. I have to use instead of That works. I see in the wtf documentation for
wtf.QuerySelectField (ext.html#module-wtforms.ext.sqlalchemy) that
"The data property actually will store/keep an ORM model instance, not
the ID." So that correlates with what I'm seeing.

I use wtfQuerySelectField in a wtf form like so:

def device_query():
...return Device.query.all()

class MaintWindowForm(wtf.Form):
...device_id = wtf.QuerySelectField(query_factory=device_query,
........get_label='name', allow_blank=False)

I my app. I have a function to edit the existing record which, when it
initially loads the form, did not properly set the "selected" property
of the device_id in the html option field. In other words, when I was
editing the record the option pulldown was not correctly set to the
current value as a default. To get it to work I edited
and changed the yield in the iter_choices method in QuerySelectField
class to hack in a comparison to the "id" column (primary key) like

#yield (pk, self.get_label(obj), obj ==
yield (pk, self.get_label(obj), obj == or ==

This correctly yields True in the third field of the yielded tuple
and, thus, sets the "selected" property to the html option that is
currently set in the sqlite3 db. The fact that I had to hack this in
makes makes me wonder if I'm just doing it all wrong. I hope I'm being
clear enough.