我试图将查询减少为单个查询,但是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)
从django official documentation:
这就是为什么对数据库进行了2次查询。也就是说,这样做可以确保您不会陷入该查询的N+1查询问题
更进一步
一些评测/调试工具(例如:Django debug toolbar)可以帮助您在为时已晚之前对页面上的复杂查询进行故障排除。另外,如果您是pytest django用户,您可能希望查看一下django_assert_num_queries。使用“原生”django测试用例,看看assertNumQueries
相关问题 更多 >
编程相关推荐