【发布时间】:2012-10-07 05:19:51
【问题描述】:
我现在正在构建一个基本的时间记录应用程序,并且我有一个使用 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
我正在尝试获取项目中所有待办事项的唯一标签列表,并且我已经设法使用集合理解使其工作,但是对于项目中的每个待办事项,我必须查询数据库以获取标签。我的理解是:
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 但是它看起来并没有得到明确的答案。我希望有人可以帮助我。谢谢!
【问题讨论】:
-
我很惊讶这个问题仍然没有答案。你找到了吗?
-
@teewuane:Taggit 最近为此添加了一项功能。
标签: django django-taggit