Reputation: 1501
I met some problems when I would like to query the ndb on GAE.
Is it possible to query the db using keywords argument?
From the document, it shows that the query string should be expression.
qry = Account.query(username == 'test_user')
Can I query or filter by a keyword argument like
search_userinfo(username='test_user')
def search_userinfo(self, **kwargs):
return UserInfo.query(**kwargs)
If not, how can I transfer the keyword argument into the expression that match ndb's condition.
Thank you.
Upvotes: 2
Views: 178
Reputation: 10360
Something like this will turn your kwargs into filters for the query:
def search_userinfo(**kwargs):
qry = UserInfo.query(*(getattr(UserInfo, k)==v for (k,v) in kwargs.items()))
return qry
Upvotes: 2
Reputation: 13138
First of all, the query should have the class name before the property name:
qry = Account.query(Account.username == 'test_user')
Next, the query uses the ==
operator while the **kwargs
uses the =
operator, so you'll have to write the query out yourself:
def search_userinfo(self, **kwargs):
return UserInfo.query(UserInfo.username == kwargs['username'])
If you want to query on a list of properties, you could chain them together like this:
def search_userinfo(self, **kwargs):
qry = UserInfo.query()
if 'username' in kwargs:
qry = qry.filter(UserInfo.username == kwargs['username'])
if 'other' in kwargs:
qry = qry.filter(UserInfo.other == kwargs['other'])
...
return qry
See NDB Query Class for more details.
Upvotes: 0