简体   繁体   中英

How does the “where()” work in SQLAlchemy

When learning SQLAlchemy, the where() clause in a query works like a magic since it expresses things quite naturally. However, I couldn't understand why it works in this way.

Consider this query:

.where(MyTable.MyColumn == 1)

In theory, the parameter passed in Python is its value (reference could be considered as pointer value from my perspective), so MyTable.MyColumn == 1 is estimated (as a value) and then passed to the function. However, how this function behaves is like "estimating the value when executing the actual query" (ie just like a real SQL WHERE clause).

I understand a similar behavior in NumPy (eg np.argwhere(myarray > 0) ) is achieved by returning the boolean value of each element estimated in this condition and then performing actions on it. Eg np.asarray([[0,1,2],[1,2,0]]) > 0 would result in array([[False,True,True],[True,True,False]], dtype=bool) and np.argwhere() simply operates on this value. I think SQLAlchemy may use a similar technique, but I still couldn't think out how they actually achieved it.

Could anyone give a brief explanation on why and how it works?

Overloading

I bet that MyTable.MyColumn overrides __eq__ . a == b is essentially the same as a.__eq__(b) .

So, MyTable.MyColumn just has to override __eq__ to return a selector object rather than a bool.

Overloading Example: Try It Online!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM