我今天遇到一个奇怪的问题,这个问题是关于为什么发生这种情况。
这是我创建的测试代码,您也可以运行和测试它->
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import os
# start of basic setup
def create_db_path() -> str:
dirname = os.path.dirname(__file__)
db_path = os.path.join(dirname, "db")
if not os.path.exists(db_path):
os.makedirs(db_path)
return db_path + "\\test.db"
class Config:
db_uri = 'sqlite:///{}'.format(create_db_path())
SECRET_KEY = 'testme'
SQLALCHEMY_DATABASE_URI = db_uri
app = Flask(__name__)
db = SQLAlchemy(app)
config = Config()
app.config.from_object(config)
class Product(db.Model):
id = db.Column(db.Integer(), unique=True, primary_key=True, autoincrement=True, nullable=False)
amount = db.Column(db.Integer(), default=0)
def update(self, amount, commit: True):
self.amount += amount
if commit:
db.session.commit()
def __repr__(self):
return f"Product('id: {self.id}', amount:'{self.amount}')"
db.create_all()
db.session.commit()
# end of basic setup
pagination_object = Product.query.paginate(per_page=2)
@app.route("/")
@app.route("/home")
def home():
global pagination_object
if len(Product.query.all()) == 0:
db.session.add(Product(amount=10))
db.session.add(Product(amount=20))
db.session.add(Product(amount=30))
db.session.add(Product(amount=40))
db.session.add(Product(amount=50))
db.session.add(Product(amount=60))
db.session.commit()
pagination_object = Product.query.paginate(per_page=2)
product = Product.query.first()
# update the query without pagination and it works and affects the actual database
product.amount += 1
db.session.commit()
# update the query within the pagination and it doest effect the actual database
pagination_object.items[0].amount += -1
db.session.commit()
# I EXPECT THAT THE TOTAL AMOUNT OF PRODUCT SHOULD NOT BE CHANGING AFTER EVERY REFRESH
print(product)
return "yay"
if __name__ == "__main__":
app.run(debug=True)
如果您多次刷新页面,我们将得到意想不到的结果。因为首先我们要在总数上加一个,然后在下一行减去它,所以我们期望下一页刷新的总数应该是相同的,但是刷新3页后的打印结果是->
Product('id: 1', amount:'11')
Product('id: 1', amount:'12')
Product('id: 1', amount:'13')
如果您测试:
print(type(pagination_object.items[0]))
print(type(product))
您将获得->
<class '__main__.Product'>
<class '__main__.Product'>
这是预期的。而且,如果我们阅读paginate()背后的代码,我们将最终看到.items是查询。 我的问题是,为什么在更新产品时应该具有相同功能的产品总数却保持不变!
感谢您的时间。