简体   繁体   中英

Google App Engine - Get from repeated StructuredProperty

I have the following structures:

class UserOther(ndb.Model):
    other_type = ndb.StringProperty(indexed = True)
    other_data = ndb.StringProperty(indexed = False)

class User(ndb.Model):
    name = ndb.StringProperty(default = "NULL", indexed = False) 
    email = ndb.StringProperty(default = "NULL", indexed = False) 
    active = ndb.BooleanProperty(default = True)

    others = ndb.StructuredProperty(UserOther, repeated = True)
    updated_at = ndb.DateTimeProperty(auto_now = True)

How can I use an User key id and a string for other_type(like "job") to get and be able to edit that information. I tried using the ancestor parameter, but perhaps I didn't do that correctly.

user_key = ndb.Key("User", user_id)
user = user_key.get()
other = UserOther.query(UserOther.other_type == "job", ancestor = user_key).get()

So if i print my user looks like this :

1425436064.0User(key=Key('User', 5171003185430528), active=True, email=u'NULL', name=u'NULL', others=[UserOther(other_data=u'0', other_type=u'job'), UserOther(other_data=u'0', other_type=u'times_worked'), UserOther(other_data=u'0', other_type=u'times_opened')], updated_at=datetime.datetime(2015, 3, 6, 10, 35, 24, 838078))

But if I print the job variable it is

 1425436759.0None

You've misunderstood how to query for structured properties. The UserOther entity doesn't live on its own, it's part of the relevant User entity, so that's what you need to query.

The documentation explains exactly how to do this, but in summary you would do:

job = User.query(User.others.other_type == "job").get()

What I would do is get the user (by id) and then filter the 'others' in code:

user = User.get_by_id(user_key_id)
for other in user.others:
    if other.other_type == 'job':
        print other.other_data  # do edits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM