首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在SQLAlchemy中标记表中的单行

问在SQLAlchemy中标记表中的单行
EN

Stack Overflow用户
提问于 2011-06-08 01:47:34
回答 1查看 1.1K关注 0票数 2

假设一个表有两列:id (整型)和mark (布尔型)。该表可以有任意数量的行,但其中恰好有一行应该将列mark设置为True。

如果我修改数据库以将另一个条目的mark标记为True,那么系统应该首先取消标记前一个条目,然后再标记请求的条目。

您将如何在Python/SQLAlchemy中实现这一点?

EN

回答 1

Stack Overflow用户

发布于 2011-06-13 08:59:50

上面的两个评论都是正确的。触发器是实现这一点的一种好方法,而且“多假一真”模式表明,也许可以使用不同的表来引用“真”行,甚至整个“真”行可能在其他地方。这里通常的模型是,您的表存储版本信息,"True“表示当前的”版本“。我通常从父记录中引用“当前”版本,或者对所有“非当前”行使用一个称为“历史”的单独表。

不管怎样,让我们看看在SQLAlchemy中做你所要求的事情的最快的方法。我们将通过ORM事件完成与INSERT/UPDATE触发器几乎相同的操作:

代码语言:javascript
复制
from sqlalchemy import Column, Integer, Boolean, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event
Base = declarative_base()

class Widget(Base):
    __tablename__ = 'widget'
    id = Column(Integer, primary_key=True)
    is_current_widget = Column(Boolean, default=False,
                        nullable=False)

@event.listens_for(Widget, "after_insert")
@event.listens_for(Widget, "after_update")
def _check_current(mapper, connection, target):
    if target.is_current_widget:
        connection.execute(
            Widget.__table__.
                update().
                values(is_current_widget=False).
                where(Widget.id!=target.id)
        )

e = create_engine('sqlite://', echo=True)
Base.metadata.create_all(e)

s = Session(e)

w1, w2, w3, w4, w5 = [Widget() for i in xrange(5)]
s.add_all([w1, w2, w3, w4, w5])
s.commit()

# note each call to commit() expires
# the values on all the Widgets so that
# is_current_widget is refreshed.

w2.is_current_widget = True
s.commit()

assert w2.is_current_widget
assert not w5.is_current_widget

w4.is_current_widget = True
s.commit()

assert not w2.is_current_widget
assert not w5.is_current_widget
assert w4.is_current_widget

# test the after_insert event

w6 = Widget(is_current_widget=True)
s.add(w6)
s.commit()

assert w6.is_current_widget
assert not w5.is_current_widget
assert not w4.is_current_widget
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6269469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档