Filter NDB requests by property (string)

with ndb and a new query class, use the filter in the query you need to use the syntax, for example:

qry = MyModel.query(MyModel.title == 'title')

How can I request a model without knowing in advance which properties I should request?

with the old way, I had a dictionary with keys and values ​​for the query and circular keys and values:

kwargs = {'title' : 'mytitle', 
          'age'   : 34 }

q = MyModel.all()

for kw, vals in kwargs.items():
    if not isinstance(vals, (list, tuple)):
        vals = (vals,)
    for v in vals:
        q.filter('%s =' % kw, v)

How can I achieve this with ndb?

+5
source share
2 answers

If this is an Expando model, or it is not important for you to check the property name, you can do it easily using GenericProperty:

kwargs = {'title' : 'mytitle', 
          'age'   : 34 }

q = MyModel.query()

for kw, vals in kwargs.items():
    if not isinstance(vals, (list, tuple)):
        vals = (vals,)
    for v in vals:
        q = q.filter(ndb.GenericProperty(kw) == v)

, ( Model) , _properties,

        q = q.filter(MyModel._properties[kw] == v)

getattr(), :

        q = q.filter(getattr(MyModel, kw) == v)

, getattr() "Python", _properties "datastore" . , -

class MyModel(ndb.Model):
  foo = StringProperty('bar')

Python foo, .

+13

- , :

kwargs = {MyModel.title : 'mytitle', 
          MyModel.age   : 34 }
q = MyModel.query()
for prop, value in kwargs.items():
  q = q.filter(prop == value)
0

All Articles