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

2024-03-28 23:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两种型号:

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)

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

^{pr2}$

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

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

有什么办法吗?谢谢你的帮助。。在


Tags: 对象nameprojecttruefieldstaskstatusrequired
1条回答
网友
1楼 · 发布于 2024-03-28 23:34:21

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

如果您不想反规范化,那么您应该异步地为项目执行gets。这将使您的请求更高效(您的成本更低,返回值更快)。在

如下所示(尚未测试):

@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。在

相关问题 更多 >