python - 基于模型的KeyProperty实例值的NDB查询

标签 python google-app-engine google-cloud-datastore

我有两个模型:

class Project:
    name = ndb.StringProperty(required=True)
    status = ndb.StringProperty()
    == Other fields ==

class Task:
    name = ndb.StringProperty(required=True)
    project = ndb.KeyProperty(kind=Project, required=True)

我需要查询对象,其中包含项目状态为“进行中”的所有任务。我正在做:

tasks = [task for task in Task.query() if task.project.get().status == "In-Progress"

这会返回任务列表,但我想要的是可用于调用 fetch_page 进行分页的查询对象。

我无法使用:tasks = Task.query(Task.project.get().status == "In-Progress")

有什么办法吗?感谢您的帮助..

最佳答案

正如其他人在评论中所说,您遇到的问题是您的项目状态不是任务的一部分。但是,为了使这种查询高效,您需要进行非规范化(这将涉及将项目状态添加到任务模型中)。

如果您不想反规范化,那么您应该异步获取项目。这将使您的请求更加高效(您的成本更低并且返回值更快)。

类似以下内容(尚未测试):

@ndb.tasklet
def callback(task):
  project= yield tast.project.get_async()
  task.fetched_project = project
  raise ndb.Return(task)

#fetch the tasks, you could do paging here.
tasks = Task.query().fetch_page(20)

#map projects onto tasks
results = yield map(callback, tasks)

#filter tasks based on project (fetched_project now exists on task) status:
tasks = [task for task in results if task.fetched_project.status == "In-Progress"]

我建议阅读有关微线程的内容 here .

关于python - 基于模型的KeyProperty实例值的NDB查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17185254/

相关文章:

c++ - ctypes 类成员访问段错误

php - Google App Engine 中的 Wordpress 卡住(保存搜索索引)

java - 为什么我的 war 在 GAE 上部署时占用这么多空间?

java - Firebase 数据库 REST 获取 orderBy 值和 equalTo

python - Google Cloud Datastore 中事务的高度一致性

python - 如何更改 NDB 记录的祖先?

python - 为什么一些 numpy 数据类型是 JSON 可序列化的,而另一些则不是?

python - 没有值的 Pandas MultiIndex

python - 在django中使用聚合(Avg())时如何解析{'value__avg' : 46. 26524716693248} 'value_avg'

python - Google App Engine 不显示任何内容