如何在烧瓶中使用QuerySelectField? [英] how to use QuerySelectField in flask?

查看:447
本文介绍了如何在烧瓶中使用QuerySelectField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这里是代码:

  def possible_book():
返回Book.query.with_entities(Book.id).all()

class AuthorForm(Form):
familyname = TextField('familyname',[validators.Required()])
firstname = TextField('firstname',[validators.Required()])
book_list = QuerySelectField('book_list',query_factory = possible_book,get_label ='title',allow_blank = True)

这是模板:

 < form action =method =postname =edit_authorenctype =多部分/格式数据> 
{{form.hidden_​​tag()}}
< p>维基百科,自由的百科全书文件:{{form.firstname(value = author.firstname)}}< / p>

Nom de famille(obligatoire):{{form.familyname(value = author.familyname)}}< / p>
< p> Livre:{{form.book_list}}< / p>

< p>< input type =submitvalue =Envoyer>< / p>
< / form>

查看:

  @ app.route('/ edit_author /< number>,methods = ['GET','POST'])
def edit_author(number):
if number == 'new':
author = []
else:
author = Author.query.filter_by(id = number).first()
form = AuthorForm()
如果form.validate_on_submit():
a = Author(firstname = form.firstname.data,familyname = form.familyname.data)
a.books = form.book_list.data

db.session.add(a)
db.session.commit()
return redirect('/ admin')
return render_template('edit_author.html',form = form,作者=作者)

模型(仅粘贴关联表和作者表,大部分列)
$ b $ pre $ $ $ $ $ $ $ $ $ $ author $ book $ db.table ',db.Integer,db.ForeignKey('author.id')),
d b.Column('book',db.Integer,db.ForeignKey('book.id'))

$ b $ class作者(db.Model):
id = db.Column(db.Integer,primary_key = True)
firstname = db.Column(db.String(64),index = True)
familyname = db.Column(db.String(120), index = True)
website = db.Column(db.String(120))
dateofbirth = db.Column(db.DateTime)
placeofbirth = db.Column(db.String(120 ))
nationality = db.Column(db.String(120))
biography = db.Column(db.Text)
photo = db.Column(db.String(120))
books = db.relationship('Book',secondary = author_book,backref = db.backref('author',lazy ='dynamic'))

我目前得到这个错误:
$ b $ pre $ UnmappedInstanceError类'sqlalchemy。 util._collections.KeyedTuple'没有映射

我真正想要的是select字段显示作者姓名和号码,并返回作者编号到应用程序(到头部的add_author函数)。

谢谢

解决方案

你有两个问题:
$ b $ ol
正如Sean Vieira在他的回答中指出的那样, code> query_factory callback应该返回一个查询,而不是结果。

  • query_factory 回调应该返回完整的实体,在你的案例书,而不是书的ID。我相信 QuerySelectField 必须尝试使用​​查询的结果,就好像它们是映射对象一样,但是(作为KeyedTuple实例返回的)不是。


  • 我认为这是编写回调函数的正确方法:

     def possible_book():
    return Book.query


    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():
        return Book.query.with_entities(Book.id).all()
    
    class AuthorForm(Form):
        familyname  = TextField('familyname', [validators.Required()])
        firstname   = TextField('firstname', [validators.Required()])
        book_list = QuerySelectField('book_list',query_factory=possible_book,get_label='title',allow_blank=True)
    

    This is the template :

     <form action="" method="post" name="edit_author" enctype="multipart/form-data">
         {{form.hidden_tag()}}
        <p>Veuillez donner son prénom (obligatoire) :    {{form.firstname(value=author.firstname)}}</p>
        <p>Nom de famille (obligatoire) : {{form.familyname(value=author.familyname)}}</p>
        <p>Livre : {{form.book_list}}</p>
    
        <p><input type="submit" value="Envoyer"></p>
     </form>
    

    View :

    @app.route('/edit_author/<number>', methods = ['GET', 'POST'])
       def edit_author(number):
       if number == 'new':
          author = []
       else:
          author = Author.query.filter_by(id = number).first()
       form = AuthorForm()
       if form.validate_on_submit():
          a = Author(firstname= form.firstname.data, familyname= form.familyname.data)
          a.books = form.book_list.data
    
           db.session.add(a)
           db.session.commit()
       return redirect('/admin')
    return render_template('edit_author.html', form = form, author = author)
    

    The model (pasted only the associative table and the author table, much of the column are out of the question)

    author_book = db.Table('author_book',
        db.Column('author', db.Integer, db.ForeignKey('author.id')),
        db.Column('book', db.Integer, db.ForeignKey('book.id'))
    )
    
    class Author(db.Model):
        id = db.Column(db.Integer, primary_key = True)
        firstname = db.Column(db.String(64), index = True)
        familyname = db.Column(db.String(120), index = True)
        website = db.Column(db.String(120))
        dateofbirth = db.Column(db.DateTime)
        placeofbirth = db.Column(db.String(120))
        nationality = db.Column(db.String(120))
        biography = db.Column(db.Text)
        photo = db.Column(db.String(120))
        books = db.relationship('Book', secondary=author_book,backref=db.backref('author', lazy='dynamic'))
    

    I currently get this error :

    UnmappedInstanceError: Class 'sqlalchemy.util._collections.KeyedTuple' is not mapped
    

    What I really want is that the select field show the author name and his number, and return the author number to the app (to the function called "add_author" on the head).

    Thank you.

    解决方案

    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
    

    这篇关于如何在烧瓶中使用QuerySelectField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆