how to use QuerySelectField in flask?

后端 未结 2 1395
情书的邮戳
情书的邮戳 2020-12-06 06:31

I am trying to have a select field filled with the results of a sqlalchemy request in a flask form.

Here are the code :

def possible_book():
    retu         


        
相关标签:
2条回答
  • 2020-12-06 07:20

    One possible problem is that wtforms.ext.sqlalchemy.fields.QuerySelectField expects a SQLAlchemy query object, not a materialized list. Simply remove the all() call from your possible_book return to return an unmaterialized query to WTForms:

    def possible_book():
        return Book.query.with_entities(Book.id)
    
    0 讨论(0)
  • 2020-12-06 07:26

    You have two problems:

    1. As Sean Vieira pointed out in his answer, the query_factory callback should return a query, not the results.

    2. The query_factory callback should return complete entities, in your case books, not book ids. I believe the QuerySelectField must be trying to use the results of the query as if they are mapped objects but the ids (returned as KeyedTuple instances) are not.

    I think this is the correct way to code the callback function:

    def possible_book():
        return Book.query
    
    0 讨论(0)
提交回复
热议问题