2012-07-03 22 views
4

违规的属性我有一个非常简单的SQLAlchemy模型如何找到一个SQLAlchemy的IntegrityError

class User(Base): 
    """ The SQLAlchemy declarative model class for a User object. """ 
    __tablename__ = 'users' 
    id = Column(Integer, primary_key=True) 
    phone = Column(String, unique=True) 
    email = Column(String, unique=True) 

当插入一个新的用户,如果电子邮件或电话是重复的可能发生的IntegrityError

有没有什么方法可以检测到哪列违反了完整性错误?或者是进行单独查询查看或存在值的唯一方法?

+0

你可以把每个都放在try/except子句中捕获IntegrityError并作出相应的反应......但是2人共享手机不可能吗? (我的妻子和我......) – mgilson

+0

@mgilson是的,我知道了,但我想知道哪两列是违规的;邮件或者电话。对于这个商业案例,需要电话号码是唯一的(通过电话登录)。 –

+2

我不认为你可以这样做,而不解析所使用的后端(或'rdbms'驱动程序)提供的异常消息。 – van

回答

-2

我通常会为此尝试使用try catch。

try: 
    session.commit() 
catch: 
str(sys.exc_info()[0]) + " \nDESCRIPTION: "+ str(sys.exc_info()[1]) + "\n" + str(sys.exc_info()[2]) 

当我遇到一个诚信的错误,我得到以下信息,我跳过特定transcation并与他们继续剩余

DESCRIPTION: (IntegrityError) duplicate key value violates unique constraint "test_code" 
DETAIL: Key (test_code)=(5342) already exists. 
'INSERT INTO test_table (pk, test_code, test_name) VALUES (%(pk)s, %(test_code)s, %(test_name)s)' { 'pk': '1', 'test_code': '5342', 'test_name': 'test' } 
2

有没有干净的方式遗憾的是这样做,但我使用在IntegrityError的原稿属性和解析模块:

try: 
    db.session.add(user) 
    db.session.commit() 
except IntegrityError, e: 
    dupe_field = parse('duplicate key value violates unique constraint "{constraint}"\nDETAIL: Key ({field})=({input}) already exists.\n', str(e.orig))["field"] 

这可能不是唯一的错误字符串IntegrityError罚球和它可以在以SQ未来的更新改变LAlchemy所以它不是理想的

相关问题