我现在正在构建一个基本的时间记录应用程序,我有一个使用 django-taggit 的 todo 模型。我的 Todo 模型如下所示:
class Todo(models.Model):
project = models.ForeignKey(Project)
description = models.CharField(max_length=300)
is_done = models.BooleanField(default=False)
billable = models.BooleanField(default=True)
date_completed = models.DateTimeField(blank=True, null=True)
completed_by = models.ForeignKey(User, blank=True, null=True)
tags = TaggableManager()
def __unicode__(self):
return self.description
我正在尝试获取项目中所有 Todos 的唯一标签列表,并且我设法使用集合理解使其工作,但是对于项目中的每个 Todo,我必须查询数据库以获取标签。我的理解是:
unique_tags = { tag.name.lower() for todo in project.todo_set.all() for tag in todo.tags.all() }
这工作得很好,但是对于项目中的每个待办事项,它运行一个单独的查询来获取所有标签。我想知道是否有任何方法可以执行类似于 prefetch_related 的操作以避免这些重复查询:
unique_tags = { tag.name.lower() for todo in project.todo_set.all().prefetch_related('tags') for tag in todo.tags.all() }
运行前面的代码给了我错误:
'tags' does not resolve to a item that supports prefetching - this is an invalid parameter to prefetch_related().
我确实看到有人在这里问了一个非常相似的问题:Optimize django query to pull foreign key and django-taggit relationship然而,它似乎从来没有得到明确的答案。我希望有人可以帮助我。谢谢!
最佳答案
Taggit 现在支持 prefetch_related
直接在标签字段上(在 0.11.0 及更高版本中,2013-11-25 发布)。
此功能是在 this pull request 中引入的.在 the test case for it ,请注意在使用 .prefetch_related('tags')
预取标签后,有 0 个额外的查询来列出标签。
关于Django-taggit prefetch_related,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926036/