假设我有一个Post实体,使用db。
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
如何为每篇博文分配ID,以及如何使用密钥检索帖子 如果我的代码是这样的。 非常感谢你
答案 0 :(得分:1)
您有两个选择:
1: Specifying your own key name(另见Using Numeric Key IDs):
new_post = Post(id="post12345", # MUST be unique!
subject="The Subject",
content="blah")
key = new_post.put()
id = key.id() # will be the "post12345" value we specified
2: Letting Cloud Datastore generate an ID to use for the key
new_post = Post(subject="The Subject",
content="blah")
key = new_post.put()
id = key.id() # will be a numeric ID generated by google
无论用于创建实体的方法(使用指定的或自动生成的id),您都可以通过id或按键检索对象,无论您使用哪个(假设两个都在下面的示例代码中可用) :
post1 = Post.get_by_id(id)
post2 = key.get()
assert post1.key == post2.key