首页 > 解决方案 > 从列表中删除 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.

标签: pythonflasksqlalchemy

解决方案


推荐阅读