Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - How does sqlachemy query method work?

I am learning sqlachemy, I'm relatively new to Python.

When I read its documentation, I saw this kind of usage, for example:

query.filter(User.name == 'ed')

Wouldn't Python evaluate the expression User.name == 'ed' and then pass the result, which is a boolean, to query.filter method?

How does this kind of syntax work? Does Python support some kind of operator overriding like C++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQLAlchemy uses the various special method hooks to overload operator behaviour.

For ==, the __eq__() method returns special objects that signify a SQL expression when compiled. To quote the documentation on the 'rich comparison' hooks:

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

See the ColumnOperators class in the SQLAlchemy source for the specific hooks implemented.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...