2

In storing data into an NDB, I'd like to obtain the name of the field from a string variable (e.g., field_name2 = "userid"). Is there a way? thanks in advance.

class Account(ndb.Model):
     username = ndb.StringProperty()
     userid = ndb.IntegerProperty()

class MainPage():
    field_name2 = 'userid'

    acct = Account.get_key(id).get() 

    acct.username = "Bob"
    acct[**field_name2**] = "001"  ## How can I do something like this?
    acct.put()
Dan McGrath
  • 39,648
  • 10
  • 95
  • 126
Jason O.
  • 2,965
  • 4
  • 29
  • 65

1 Answers1

5

Because ndb.Models behave like normal Python objects, you can access fields dynamically with Python getattr and setattr.

In your example:

    setattr(acct, field_name2, "001")

Give it a whirl at http://shell.appspot.com See also: How to dynamically access class properties in Python?

Community
  • 1
  • 1
ckhan
  • 4,676
  • 23
  • 26