Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy id equality vs reference equality

I'm working with SQLAlchemy for the first time and was wondering...generally speaking is it enough to rely on python's default equality semantics when working with SQLAlchemy vs id (primary key) equality?

In other projects I've worked on in the past using ORM technologies like Java's Hibernate, we'd always override .equals() to check for equality of an object's primary key/id, but when I look back I'm not sure this was always necessary.

In most if not all cases I can think of, you only ever had one reference to a given object with a given id. And that object was always the attached object so technically you'd be able to get away with reference equality.

Short question: Should I be overriding eq() and hash() for my business entities when using SQLAlchemy?

like image 455
lostdorje Avatar asked Nov 18 '11 07:11

lostdorje


1 Answers

Short answer: No, unless you're working with multiple Session objects.

Longer answer, quoting the awesome 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.

like image 132
tuomur Avatar answered Sep 22 '22 17:09

tuomur