python - 从列表中删除 Sqlalchemy - Flask current_user
问题描述
我有一个奇怪的行为,我现在无法解释。
一个用户可以在多本书中,而一本书可以有许多用户。
假设我们有一个用户表
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
books = db.relationship(
'Book',
secondary='user_book',
backref='members',
lazy='dynamic')
以及一个书桌:
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
和关联表:
class UserBook(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer(),
db.ForeignKey('user.id', ondelete='CASCADE'))
book_id = db.Column(
db.Integer(),
db.ForeignKey('book.id', ondelete='CASCADE'))
用户有一个方法离开一本书:
def leave_book(self, book):
self.books.remove(book)
此方法经过单元测试并且可以正常工作。
问题是在进行 API 调用和使用 current_user 时:
@book_bp.route('/api/book/leave', methods=['DELETE'])
@login_required
def api_book_leave():
book_id = request.json['book_id']
book = Book.query.filter_by(id=book_id).first()
# one of the following snippet is inserted here [1]
try:
db.session.commit()
except exc.SQLAlchemyError:
db.session.rollback()
raise InternalServerError(
description='An error occurred while leaving book.')
return jsonify()
(请记住,我从这个片段中剥离了检查和验证)
以下是可以替代 [1] 的不同可能性:
current_user.leave_book(book)
# This doesn't remove the book from the user book list.
book.members.remove(current_user)
# This removes the book from the user book list.
user = User.query.filter_by(id=current_user.id).first()
user.leave_book(book)
# This removes the book from the user book list.
我很困惑为什么如果我在 current_user 上使用它时查询不起作用,但是如果我首先查询具有 current_user 的 id 的用户,然后删除这本书,它就起作用了。
任何提示表示赞赏:)
编辑:有关 current_user 的附加信息,它变得越来越奇怪:
user = User.query.filter_by(id=current_user.id).first()
print(current_user == user) # returns True
user.leave_book(book)
# This removes the book from the user book list.
解决方案
推荐阅读
- apache-spark - 如何使用不同的df列更新现有列
- tensorflow - SSD mobilenet 模型无法检测到更远距离的物体
- amazon-web-services - Lambda Kinesis Stream 消费者并发问题
- machine-learning - glove 和 word2vec 之间的主要区别是什么?
- specflow - SpecFlow+ Runner 服务器:在 \packages\SpecRun.Runner.xyz\tools 中找不到“服务器”目录
- android - scrollTo 在带有 alpha 的视图后面时不起作用
- .net - vb.net直接分配属性和使用invoke方法的区别
- php - 如何连续执行我的脚本以发送邮件?
- php - 如何修复包含动态输入字段的代码?
- reactjs - 单击显示选项按钮时如何在特殊表格行中呈现组件(选项菜单)