我有一个看起来像这样的模型:
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/