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
  • 41,220
  • 11
  • 99
  • 130
Jason O.
  • 3,168
  • 6
  • 33
  • 72

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,771
  • 24
  • 26