Django Orm预取领域从手动加入表中有关多一关系的关系表
更改Django模型后,我正面临N-plus-1查询爆炸,我认为这是因为我必须从手动加入表中重新查询字段,
示例
class Dashboard(models.Model):
team: models.ForeignKey = models.ForeignKey("Team", on_delete=models.CASCADE)
items = models.ManyToManyField("Item", related_name="dashboards", through="DashboardItem")
class Item(models.Model):
deleted: models.BooleanField = models.BooleanField(default=False)
class DashboardItem(models.Model):
class Meta:
unique_together = (
"dashboard",
"item",
)
dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE)
item = models.ForeignKey("Item", on_delete=models.CASCADE)
combo_hash: models.CharField = models.CharField(max_length=400, null=True, blank=True)
如果我要查询一个 仪表板,知道我只能在2个查询中查看其项目,
dashboards = Dashboard.objects.filter(items__deleted==False).select_related("team").prefetch_related('items')
但我可以在代码中进行此操作,尽管有机会在仪表板或物品上进行预取。我发现我需要
DashboardItem.objects.filter(item=item,dashboard=dashboard).first().combo_hash
在加载仪表板或物品时如何通过表上的表中的表格进行预取值?
I'm facing an n-plus-1 query explosion after changing a Django model and I think it is because I am having to re-query for fields from a manual join table
As a stripped-down example
class Dashboard(models.Model):
team: models.ForeignKey = models.ForeignKey("Team", on_delete=models.CASCADE)
items = models.ManyToManyField("Item", related_name="dashboards", through="DashboardItem")
class Item(models.Model):
deleted: models.BooleanField = models.BooleanField(default=False)
class DashboardItem(models.Model):
class Meta:
unique_together = (
"dashboard",
"item",
)
dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE)
item = models.ForeignKey("Item", on_delete=models.CASCADE)
combo_hash: models.CharField = models.CharField(max_length=400, null=True, blank=True)
If I'm querying for a dashboard and know I need to see its items with only 2 queries I can do this
dashboards = Dashboard.objects.filter(items__deleted==False).select_related("team").prefetch_related('items')
but later in the code, despite having the opportunity to prefetch on dashboard or item. I find I'm needing to do
DashboardItem.objects.filter(item=item,dashboard=dashboard).first().combo_hash
How do I prefetch values on the manual through table when I load the dashboard or item?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以按表在自定义上以相同的方式进行自定义,以进行反向外键关系,因此,使用
dashboarditem_set
:与您的
item> item
模型相同。You can prefetch on your custom through table the same way you do it for reverse foreign key relations, so by using
dashboarditem_set
:It will be the same usage with your
Item
model.