如何使用sqlalchemy IntegrityError查找违规属性

问题描述 投票:6回答:3

我有一个非常简单的SqlAlchemy模型

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

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

python sqlalchemy integrity
3个回答
3
投票

遗憾的是,没有干净的方法可以做到这一点,但我在IntegrityError和parse模块上使用了orig属性:

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抛出的唯一错误字符串,它可能会在SQLAlchemy的未来更新中发生变化,因此它并不理想


0
投票

您可以使用以下方式相应地获取基础代码,消息和格式化消息。

except exc.IntegrityError as e:
       errorInfo = e.orig.args
       print(errorInfo[0])  #This will give you error code
       print(errorInfo[1])  #This will give you error message

顺便说一下,你必须从sqlalchemy导入exc:from sqlalchemy import exc如果你需要任何其他信息,请告诉我。我可以尝试一下。

有关sqlalchemy exc的更多信息,请找到代码:https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/exc.py


-3
投票

我通常会使用try catch。

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

当我遇到完整性错误时,我收到以下消息,并跳过该特定的传输并继续其余的

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' }
© www.soinside.com 2019 - 2024. All rights reserved.