如果自上次输入以来值没有更改,如何避免向 SQLAlchemy 添加行?
我将通过 SQLAlchemy 跟踪数据库中某些值的演变:我将它们作为(键,值)对的序列,并且我希望每个键的值很少改变。
我正在使用 SQLAlchemy 和 声明性,模型如下所示:
class Item(Base):
timestamp = Column(DateTime)
key = Column(Unicode(16))
value = Column(something...)
我想在数据库中存储诸如(时间戳,键,值)之类的行,并避免存储新条目,如果价值自上次记录以来没有改变,同时保留了过去值的整个历史记录。在伪 python 中:
for foo in new_items:
query = session.query(Item).filter_by(key=foo.key)
latest = query.order_by(Item.timestamp.desc()).first()
if foo.value == latest.value:
continue # nothing changed, ignore the new item
else:
session.add(foo)
session.commit()
我应该采用像上面这样的简单方法吗?不知怎的,它给我的印象是代码不好看。至少我可能会将测试添加为 Item 的方法。
有更好的方法吗?更好并不一定意味着更快,可能只是更Pythonic或更好看的代码。
I'm going to track the evolution of some values with a database via SQLAlchemy: I get them as a sequence of (key, value) pairs and I expect the values for each key to change rarely.
I'm using SQLAlchemy with declarative, the model looks like:
class Item(Base):
timestamp = Column(DateTime)
key = Column(Unicode(16))
value = Column(something...)
I'd like to store rows like (timestamp, key, value) in the database and avoid storing new entries if the value didn't change since the last one recorded, while keeping the whole history of past values. In pseudo python:
for foo in new_items:
query = session.query(Item).filter_by(key=foo.key)
latest = query.order_by(Item.timestamp.desc()).first()
if foo.value == latest.value:
continue # nothing changed, ignore the new item
else:
session.add(foo)
session.commit()
Should I go with a naive approach like the one above? It somehow strikes me as not-good-looking code. At least I'd maybe add the test as a method on Item.
Is there some better way to do that? Better does not necessarily mean quicker, could be just more pythonic or better looking code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道有两种方法可以做到这一点。这是你的方法:
或
第一个有竞争条件。我倾向于使用第二种模式。
I am aware of two ways to do that. There's your approach:
or
The first one has a race condition. I tend to use the second pattern.