user1343035
user1343035

Reputation: 265

Calling GAE NDB query with dynamic property name

Google AppEngine NDB queries are strange beasts. Say I have a class (and ndb entity) of Car
with color and weight properties. I can do

Car.query(Car.color == "blue")

I've never seen any Python 2 documentation on this kind of "function call". How many arguments are being passed? Logically it would be one that is a Boolean, but apparently "query" can find out the source code of that argument and get Car.color, ==, and "blue". Is it possible for developers to define these kind of functions, or is this some compiler hack?

My real problem is that I have a user input dialog that has fields for the class ("Car" in this case) the property ("color" in this case) and the value, ("blue" in this case). How can I construct and call a query that takes those inputs?

Upvotes: 2

Views: 615

Answers (1)

Dmytro Sadovnychyi
Dmytro Sadovnychyi

Reputation: 6201

This is done by python magic methods, your sample uses __eq__.

To construct a query you can use something like this:

Car.query(getattr(Car, 'color') == 'red')

Be sure to check if property exists by calling hasattr(Car, 'color')

Upvotes: 4

Related Questions