我对我想要推迟的一个表有一个独特的约束,这是Postgresql根据我的理解支持的东西,但我似乎无法找到我可以告诉我的操作在哪里这样做使用ORM时的SQLAlchemy(一般情况下,不仅仅是这种情况)。我正在使用bulk_update_mappings()
函数,约束是__table_args__
下的第2个。这是我需要使用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()
答案 0 :(得分: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()