问题
I'm having some trouble understanding how entities and keys work in Google App Engine NDB.
I have a post
entity and a user
entity. How do I set the user_key
on post
to user
?
In the interactive console, I have this so far:
from google.appengine.ext import ndb
from app.lib.posts import Post
from app.lib.users import User
from random import shuffle
users = User.query()
posts = Post.query().fetch()
for post in posts:
post.user_key = shuffle(users)[0]
post.put()
I'm just trying to set up some seed data for development. I know this probably isn't the ideal way to set things, but my first question is:
- How do I get a key from an entity (the reverse is described in the docs)
- How do I set associations in ndb?
回答1:
try:
post.user_key = shuffle(users)[0].key
回答2:
Maybe this helps to understand the NDB. I had the same questions with you.
class Person(ndb.Expando):
pass
class Favourite(ndb.Expando):
pass
class Picture(ndb.Expando):
pass
person = Person()
person.put()
picture = Picture()
picture.put()
fav = Favourite(parent=person.key,
person=person.key,
picture=picture.key
)
fav.put()
回答3:
- Verify that shuffle works in this case, as User.query() returns an iter, not a list. (You can convert it to a list using shuffle( [ x for x in users ] ). Beware, this list could be looong.
- NDB has some really wired behavior sometimes, so id recommend you dont store an NDB-Key, but its serialized string, which is also compatible to ext.db: post.user_key = shuffle( [ x for x in users ] ).key.urlsafe()
- You could use KeyProperty for associations. If you need a more fine-graned control over your relations, you must implement them yourself. See https://developers.google.com/appengine/docs/python/ndb/properties#structured
来源:https://stackoverflow.com/questions/14192331/how-to-set-an-ndb-keyproperty