PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 20, 2022

[FIXED] How does sqlachemy query method work?

 December 20, 2022     python, sqlalchemy, syntax     No comments   

Issue

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++?


Solution

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.



Answered By - Martijn Pieters
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing