gpt4 book ai didi

python - sqlalchemy id 相等与引用相等

转载 作者:太空狗 更新时间:2023-10-29 20:56:53 24 4
gpt4 key购买 nike

我是第一次使用 SQLAlchemy,我想知道...一般来说,在使用 SQLAlchemy 与 id(主键)相等时,依赖 python 的默认相等语义是否足够?

在我过去使用 ORM 技术(如 Java 的 Hibernate)从事的其他项目中,我们总是重写 .equals() 来检查对象的主键/id 是否相等,但当我回顾时,我不确定这是否总是必要的。

在我能想到的大多数(如果不是全部)情况下,您只有一个对具有给定 ID 的给定对象的引用。而且该对象始终是附加对象,因此从技术上讲,您可以摆脱引用相等性。

简短的问题:在使用 SQLAlchemy 时,我是否应该为我的业务实体覆盖 eq() 和 hash()?

最佳答案

简短回答:不,除非您使用多个 Session 对象。

更长的答案,引用了很棒的 documentation :

The ORM concept at work here is known as an identity map and ensures that all operations upon a particular row within a Session operate upon the same set of data. Once an object with a particular primary key is present in the Session, all SQL queries on that Session will always return the same Python object for that particular primary key; it also will raise an error if an attempt is made to place a second, already-persisted object with the same primary key within the session.

关于python - sqlalchemy id 相等与引用相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8179068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com