与M2M相关的Django预取_,通过关系

2024-09-30 03:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将查询减少为单个查询,但是queryset返回2个查询。我尝试了一些方法,但没有改变

Models.py

class Match(models.Model):
    ...
    participant = models.ManyToManyField(TournamentTeam, through='MatchParticipant')
    ...
class MatchParticipant(models.Model):
    match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, blank=True)
    team = models.ForeignKey(TournamentTeam, on_delete=models.SET_NULL, null=True, blank=True)

views.py

queryset = Match.objects.prefetch_related(
        Prefetch(
            'participant',
            queryset=MatchParticipant.objects.select_related(
                'match','team'
            ),
        ),
    ).select_related('some_foreignkey',).get(slug=slug)

Tags: pytruemodelonmodelsmatchdeleteclass
1条回答
网友
1楼 · 发布于 2024-09-30 03:23:16

django official documentation

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, in addition to the foreign key and one-to-one relationships that are supported by select_related.

这就是为什么对数据库进行了2次查询。也就是说,这样做可以确保您不会陷入该查询的N+1查询问题

更进一步

一些评测/调试工具(例如:Django debug toolbar)可以帮助您在为时已晚之前对页面上的复杂查询进行故障排除。另外,如果您是pytest django用户,您可能希望查看一下django_assert_num_queries。使用“原生”django测试用例,看看assertNumQueries

相关问题 更多 >

    热门问题