简体   繁体   中英

Python flask, a cleaner way to update a SQLAlchemy record

is there any way to perform database update in flask better than this:

@author_blueprint.route("/updateAuthor/<int:author_id>", methods=["GET","POST"])
def updateAuthor(author_id):
    author = Author.query.get(author_id)
    form = AuthorForm(request.form, obj=author)
    if request.method == "POST" and form.validate_on_submit():
        author.firstName = form.firstName.data //line 6
        author.lastName = form.lastName.data //line 7
        author.university = form.university.data.name //line 8
        author.department = form.department.data.name //line 9
        author.email = form.email.data //line 10
        db.session.commit()
        flash("Updated author Successfully")
        return redirect(url_for("author.createAuthor"))
    authors = author.query.all()
    return render_template("author/author.html", title="authors", form=form, authors=authors)

my record is updated using this way but I done want to write all the fields one by one to do the update like in lines 6 to 10

just warp it up with some function sa

def update(author, form):
    author.firstName = form.firstName.data
    author.lastName = form.lastName.data 
    author.university = form.university.data.name
    author.department = form.department.data.name
    author.email = form.email.data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM