SQLAlchemy ORM - 延迟约束检查

问题描述 投票:1回答:1

我对我的一个表有一个独特的约束我想推迟,这是Postgresql从我的理解支持的东西,但我似乎无法在使用ORM时在SQLAlchemy中找到我可以告诉我的操作的地方(一般情况下,不仅仅是这种情况)。我正在使用bulk_update_mappings()函数,约束是__table_args__下的第二个。这是我需要使用SQLAlchemy Core还是创建自己的SQL语句来实现的?

class Question(Base):
    QuestionType = enum.Enum('QuestionType', 'mcq')
    __tablename__ = 'questions'
    id = Column(Integer, primary_key=True)
    type = Column(Enum(_QuestionType), nullable=False)
    description = Column(String, nullable=False)
    question_order = Column(Integer, nullable=False)
    question_set_id = Column(Integer, ForeignKey('question_sets.id', ondelete='cascade'), nullable=False)

    question_set = relationship('QuestionSet', back_populates='questions')

    __table_args__ = (
        UniqueConstraint('question_set_id', 'description'),
        UniqueConstraint('question_set_id', 'question_order', deferrable=True)
    )
    __mapper_args__ = {
        'polymorphic_identity': 'question',
        'polymorphic_on': type,
    }

#from another class
def reorder(self, new_order, db):
    order = [{'id':i, 'question_order': index} for index, i in enumerate(new_order)]
    db.bulk_update_mappings(Question, order)
    db.commit()
python python-3.x postgresql sqlalchemy
1个回答
1
投票

鉴于db是您的会话实例,请运行

db.execute('SET CONSTRAINTS ALL DEFERRED')

在批量操作之前,为了defer all deferrable constraints在当前的交易中。请注意not all constraints are deferrable,即使他们被宣布为这样。如果您知道其名称,则可以选择仅推迟唯一约束,例如unique_order:

def reorder(self, new_order, db):
    order = [{'id':i, 'question_order': index} for index, i in enumerate(new_order)]
    db.execute('SET CONSTRAINTS unique_order DEFERRED')
    db.bulk_update_mappings(Question, order)
    db.commit()
© www.soinside.com 2019 - 2024. All rights reserved.