python - Django:重复过滤查询集的最有效方法

标签 python django django-queryset

我有一个看起来像这样的模型:

class Item(models.Model):
    name = models.CharField()
    type = models.CharField()
    tags = models.models.ManyToManyField(Tags)

为了呈现给定的 View ,我有一个 View 根据类型显示项目列表。所以在我看来,有这样的查询:

items = Item.objects.filter(type='type_a')

所以这很简单直接。现在我对 View 有额外的要求。为了满足该要求,我需要构建一个将标签与项目相关联的字典。所以我正在寻找的输出是这样的:

{
    'tag1': [item1, item2, item5],
    'tag2': [item1, item4],
    'tag3': [item3, item5]
}

最有效的方法是什么?有什么方法可以做到这一点而无需为每个标签重新查询数据库?

最佳答案

可以查看prefetch_related它可能对您有帮助:

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different... prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related...

所以最后您要么执行多个查询,要么使用 prefetch_related,它将对对象执行一些 Python 连接。

关于python - Django:重复过滤查询集的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23178868/

相关文章:

python - 如何在Python中的列表中存储多个字符串?

Python 使用追加写入元组错误

Django查询: field is substring

python - 从 Django Queryset 获取值列表的最有效方法

python - 如何将二进制文件数据读入数组?

python - 如何打印充满 "chaos question marks"的字符串的值

python - 如何计算全局覆盖率?

django-tables2:在渲染方法中使用请求用户

python - 在 Django 查询集过滤器中,如何检查 json 字段中的至少一个键是否具有非空值?

django - 最佳 django manytomany 查询