How to delete a record from the database stored with Flask SQLAlchemy? I did it like this and it's still showing an error like this :
sqlalchemy.exc.InvalidRequestError: Instance '<users at 0x1d6436a3be0>' is not persisted
This is the database name:
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
This is the method i used:
@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"))
CodePudding user response:
You are trying to delete a new instance of user. Which you created with
usr = users(user, email)
Since user, email is not the primary key, this is a different user instance than the user you're trying to delete. You should delete found_user. eg:
if found_user:
db.session.delete(found_user)
db.session.commit()
flash("An Account has been Deleted!")