我有两个模型:
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/