![](/img/trans.png)
[英]Python - SQLAlchemy using exists() to check if data already in table?
[英]SQLAlchemy: Check if object is already present in table
我有一個類Item
其id
是主鍵並自動生成。 現在我從其他一些外部源讀取數據,創建一個Item
對象,並且需要檢查我的items
表中是否已存在此對象。 我該怎么做?
最有效的方法是使用exists()
q = session.query(Item.id).filter(Item.email==email)
session.query(q.exists()).scalar() # returns True or False
您可以查詢具有相同屬性的項目,並檢查計數是否大於零。
if session.query(Item.id).filter(Item.email==newItem.email,
Item.type==newItem.type).count() > 0:
// item exists
你可以嘗試類似的東西:
from sqlalchemy import exc
try:
session.add(item)
session.commit()
except exc.IntegrityError:
session.rollback()
print 'This item fails one of the unique/foreign key checks!'
except:
print 'There was another error'
raise
else:
print 'Everything is OK'
這有一個問題,它作用於提交,然后回滾......
另一個選項,如果您可以單獨檢查屬性,那么這可能有效:
session.query(Item).filter_by(x=item.x, y=item.y).count() == 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.