nav*_*nav 5 python postgresql sqlalchemy python-3.x
我对我想要推迟的一个表有一个独特的约束,据我所知,这是 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()
Run Code Online (Sandbox Code Playgroud)
鉴于这db是您的会话实例,请运行
db.execute('SET CONSTRAINTS ALL DEFERRED')
Run Code Online (Sandbox Code Playgroud)
在批量操作之前,以推迟当前事务中的所有可推迟约束。请注意,并非所有约束都是可延迟的,即使它们是这样声明的。如果您知道唯一约束的名称,例如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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3000 次 |
| 最近记录: |