幕布斯7119047
2023-02-07 13:43:47
我正在嘗試從我的數(shù)據(jù)庫中刪除數(shù)據(jù),但我的 Web 應(yīng)用程序返回此錯誤:File "C:\Users\q\Pyc\Flask\basic_of_flask\SQL Database with flask\Database in view\adoption_sit.py", line 78, in del_puppup = db.session.get(id)AttributeError: 'scoped_session' object has no attribute 'get'看看下面我的代碼import osfrom flask import Flask, redirect, render_template, url_forfrom flask_migrate import Migratefrom flask_sqlalchemy import SQLAlchemyfrom form import AddForm, DelFormapp = Flask(__name__)app.config['SECRET_KEY'] = 'mysecretkey'########################################### SQL DATABASE SECTION ####################################################basedir = os.path.abspath(os.path.dirname(__file__))app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Falsedb = SQLAlchemy(app)Migrate(app, db)################################################ Models ################################################################class Puppy(db.Model): __tablename__ = 'puppies' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text) def __init__(self, name): self.name = name def __repr__(self): return f"Puppy name is {self.name}."################################################## VIEW FUNCTIONS -- HAVE FORM ########################################################@app.route('/')def index(): return render_template('home.html')@app.route('/add', methods=['GET', 'POST'])def add_pup(): form = AddForm() if form.validate_on_submit(): name = form.name.data new_puppy = Puppy(name) db.session.add(new_puppy) db.session.commit() return redirect(url_for('list_pup')) return render_template('add.html', form=form)@app.route('/list_pup')def list_pup(): puppies = Puppy.query.all() return render_template('list.html', puppies=puppies)
1 回答

烙印99
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個贊
del_pup()我猜你在功能上做錯了事
[..]
pup = db.session.get(id) # here
您需要Puppy使用給定的對象獲取對象id:
@app.route('/delete', methods=['GET', 'POST'])
def del_pup():
form = DelForm()
if form.validate_on_submit():
id = form.id.data
# pup = db.session.get(id) # wrong way
pup = Puppy.query.filter_by(id=id).first()` # here
db.session.delete(pup)
db.session.commit()
return redirect(url_for('list_pup'))
return render_template('delete.html', form=form)
添加回答
舉報
0/150
提交
取消