如何从 flask-SQLAlchemy 的数据库中删除一条记录?

How to delete a record from a database in flask-SQLAlchemy?

如何从 Flask SQLAlchemy 存储的数据库中删除一条记录? 我是这样做的,但它仍然显示这样的错误:

sqlalchemy.exc.InvalidRequestError: Instance '<users at 0x1d6436a3be0>' is not persisted

这是数据库名称:

db = SQLAlchemy(app)

class users(db.Model):
    _id = db.Column("id", db.Integer, primary_key=True)
    name = db.Column("name", db.String(100))
    email = db.Column("email", db.String(100))


    def __init__(self, name, email):
        self.name = name
        self.email = email

这是我使用的方法:

@app.route("/view", methods=["POST", "GET"])
def view():

    if "user" in session:
        user = session["user"]
        
        if request.method == "POST":
            user = request.form["nm"]
            session["user"] = user

            found_user = users.query.filter_by(name=user).first()
            email = found_user.email

            if found_user:
                usr = users(user, email)
                db.session.delete(usr)
                db.session.commit()
                flash("An Account has been Deleted!")
            else :
                flash("Name is not found")

        else:
            return render_template("view.html", values=users.query.all())

    else:
        flash("Please Login First")
        return redirect(url_for("login"))

您正在尝试删除一个新的用户实例。您使用

创建的
usr = users(user, email)

因为用户,电子邮件不是主键,这是一个不同于您要删除的用户的用户实例。您应该删除 found_user。 例如:

if found_user:
    db.session.delete(found_user)
    db.session.commit()
    flash("An Account has been Deleted!")