我试图在烧瓶表单中填充一个 sqlalchemy 请求的结果的选择字段。
这是代码:
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)
这是模板:
<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>
看法 :
@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)
模型(只贴关联表和作者表,大部分列都不行)
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'))
我目前收到此错误:
UnmappedInstanceError: Class 'sqlalchemy.util._collections.KeyedTuple' is not mapped
我真正想要的是选择字段显示作者姓名和他的号码,并将作者号码返回给应用程序(返回到头部称为“add_author”的函数)。
谢谢你。