Django-taggit prefetch_related

标签 django django-taggit

我现在正在构建一个基本的时间记录应用程序,我有一个使用 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/

相关文章:

Django-taggit。模型中的多个标签。检索数据

python - 删除未被任何其他对象使用的标签

mysql - Django 过滤器和 MySQL(子字符串,长度)

collectstatic 时 Django gettext 错误

javascript - 无法将 CSRF token 添加到 Django POST 请求的 XMLhttpRequest

python - 从 Django 模型类中解耦域类

python - ValueError : set_wakeup_fd only works in main thread on Windows on Python 3. 8 使用 Django 3.0.2 或 Flask 2.0.0

python - 为什么我使用 Tag.models.all() 后 Taggit (Django-Tag) 就无法工作

django - 我如何使用 taggit-selectize 以便所有用户创建的标签都显示在自动完成中?

django - 如何限制 django-taggit 只接受小写单词?