python - 如何获得 NDB 数据存储的复合 ID

标签 python google-app-engine

以前,我有以下实体

class User(ndb.Model):
    name = ndb.StringProperty(required = True)
    timestamp = ndb.DateTimeProperty(required = True)

我使用 name 作为 id,通过以下方式编写我的代码

user = User.get_or_insert(name, name=name, 
    timestamp=datetime.datetime.fromtimestamp(user_timestamp))

通过将 name 作为 id,我可以使用 name 执行快速读取或更新。


现在,我决定将我的实体更改为以下内容,并将 nametype 作为复合 id。

class User(ndb.Model):
    name = ndb.StringProperty(required = True)
    type = ndb.StringProperty(required = True)
    timestamp = ndb.DateTimeProperty(required = True)

引用后https://stackoverflow.com/a/5454623/72437

我的第一个想法是,通过连接 nametype,它实现了我的复合 id 目的。

user = User.get_or_insert(name+type, name=name, type=type
    timestamp=datetime.datetime.fromtimestamp(user_timestamp))

很快,我意识到这个想法是有缺陷的。由于以下情况会产生冲突。

name    type    id 
-------------------------   
cheok   paid    cheokpaid
cheokp  aid     cheokpaid

2 个不同的用户最终拥有相同的 ID。

我想知道,什么是适合我的正确方法

  1. 拥有基于nametype 的复合 id
  2. 使用nametype 快速阅读或更新

最佳答案

为什么不在连接名称和类型时使用分隔符。然后您的代码将按原样工作并解决您的问题。

例如,如果您使用“_”作为分隔符,则

cheok   paid  become cheok_paid   and
cheokp  aid   become cheokp_aid  

关于python - 如何获得 NDB 数据存储的复合 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371784/

相关文章:

python - 如何在模板内部确定图像是否已上传?

python - subprocess.check_output 与 subprocess.call 的性能

python - key 错误 : 'PATH_INFO' when using Pydev and Google App Engine

python - 如何以编程方式在 Google Appengine (Python) 中获取 SDK 版本?

python - 将多态对象从 C++ 传递给 python 函数

python - Perlin 噪声看起来太网格化

python - 我想添加一个可以加载下一个图像文件并将其显示到 Canvas 的按钮

java - 检索 Google 委托(delegate)联系人

node.js - 使用 Google Cloud Storage 存储的图像的属性

python - 为什么我无法从 jinja 模板中访问 Google 应用引擎实体的 key