如何解决为什么删除的数据仍显示在Sqlalchemy Flask中?
我正在执行一项任务,使用sqlalchemy将添加的页面删除到postgresql数据库中。 该页面正在从服务器中删除,但无法从数据库中删除。 这是删除页面的功能:
def delete_page(self,page_id,application):
# removed
removed_from_everyone = True
# fro campaign_id
for campaign_id in self.bandit_campaigns:
if page_id in self.bandit_pages[campaign_id].keys():
# If the page is active
if self.bandit_pages[campaign_id][page_id]:
removed_from_everyone = False
# check if the page exist adn if it's not used by anyone
if page_id in self.structure.keys() and removed_from_everyone:
del self.structure[page_id]
# for all the campaign
for campaign_id in self.bandit_campaigns:
# puts it in the new structure
del self.bandit_pages[campaign_id][page_id]
application.logger.info(f'page_id: {page_id}')
application.logger.info(f'type page_id: {type(page_id)}')
# remove arm
self.remove_arm(page_id)
application.logger.info(f'pages: {self.pages}')
# Backup of the situation,in this case save only the pages
# pickle.dump(self.structure,open('structure.pickle',"wb"))
# this one store the last know status
# pickle.dump(self.bandit_pages,open('bandit_pages.pickle',"wb"))
try:
pg = Structure.query.filter_by(page_url=page_id)
db.session.delete(pg)
bp = Bandit_pages.query.filter_by(campaign_id=campaign_id)
db.session.delete(bp)
db.session.commit()
except Exception as e:
print("exception in new page deletion",e)
db.session.rollback()
这是Structure和Bandit_page表创建的代码:
class Structure(db.Model):
__tablename__ = 'structure'
arm_id = db.Column(db.Integer,primary_key=True)
page_url = db.Column(db.String())
def __init__(self,arm_id,page_url):
self.arm_id = arm_id
self.page_url = page_url
class Bandit_pages(db.Model):
__tablename__ = 'bandit_pages'
campaign_id = db.Column(db.String())
arm_id = db.Column(db.Integer)
status = db.Column(db.Boolean,default=False)
__table_args__ = (
PrimaryKeyConstraint('campaign_id','arm_id'),{},)
def __init__(self,campaign_id,status):
self.campaign_id = campaign_id
self.arm_id = arm_id
self.status = status
我尝试了一种使用for循环删除它们的方法,然后将其删除,但这没有帮助。 另外,添加页面的功能类似于删除页面的功能,因此我不清楚我在哪里出错。请帮帮我。谢谢!
解决方法
您可以尝试以下命令->
db.session.delete(me)
,db.session.commit()
您的代码很复杂:您使用相同的循环几次并使用相同的变量名。
因此,您尝试仅从self.bandit_campaigns
中删除最后一个值:
bp = Bandit_pages.query.filter_by(campaign_id=campaign_id)
db.session.delete(bp)
db.session.commit()
此外,我不确定self.self.bandit_campaigns
的键是否是字符串ID,也请检查一下。
要删除self.bandit_campaigns
中的所有元素,可以使用:db.session.query(Bandit_pages).filter(Bandit_pages.campaign_id.in_(your_list_of_values)).delete()
所以我自己解决了这个问题,发现这是一个琐碎的错误,被忽略了。
try:
Structure.query.filter_by(page_url='ml3',arm_id=1).delete() # .all()
#db.session.delete(pg)
Bandit_pages.query.filter_by(campaign_id='96879533',arm_id=1).delete() # .all()
#db.session.delete(bp)
db.session.commit()
db.session.expire_all()
except Exception as e:
print("exception in new page deletion",e)
db.session.rollback()
这段代码(我改变了几行)效果很好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。