我试图从我的订阅者列表中删除用户,但整个订阅者会自动删除。
这是我的订阅功能:
def subscribe(self, user_id):
if not self.is_subscriber(user_id):
db.engine.execute(
subscribers.insert(),
client_id = self.id,
user_id = user_id
)
db.session.commit()
else:
return False
取消订阅功能:
def unsubscribe(self, user_id):
if self.is_subscriber(user_id):
db.engine.execute(
subscribers.delete(),
client_id = self.id,
user_id = user_id
)
db.session.commit()
else:
return False
如果我试图取消订阅它应删除该特定用户,但在我的情况下,整个用户从表中删除,为什么,请,任何人都可以帮助解决这里的问题?
如果我试图从查询中删除client_id并删除user_id,我会收到此错误:
UnmappedInstanceError: Class '__builtin__.int' is not mapped
还有 db.session.delete(user_id)命令!!
我也创建了这个函数,我也得到了同样的错误:
def unsubscriber(self, user_id):
select_subscribers = subscribers.select(
db.and_(
subscribers.c.user_id == user_id,
subscribers.c.client_id == self.id
)
)
rs = db.engine.execute(select_subscribers)
return False if rs.rowcount == 0 else db.session.delete(user_id),
db.session.commit()
答案 0 :(得分:1)
如果你正在使用flask-sqlalchemy,你可以简化很多这样做,以充分利用sqlalchemy的强大功能。你不应该像这样直接访问引擎,除非你有更高级的用例,你应该use the session
E.g。您已经映射了这样的数据模型:
class Subscriber(db.Model):
user_id = db.Column(db.Integer, primary_key=true)
client_id = ....
....
# method to add new subscriber
def __init__(self, user_id, client_id)
self.user_id = user_id
self.client_id = client_id
@app.route('/subscribe/')
def subscribe():
# add a subscriber with user id 21, client 543
new = Subscriber(21, 543)
db.session.add(new)
db.session.commit()
@app.route('/unsubscribe/')
def unsubscribe():
# remove subscriber
Subscriber.query.filter_by(user_id=21, client_id=543).delete()
db.session.commit()