使用prefetch_related时如何最好地包含来自Django ManyToManyField自定义中间模型的字段?

时间:2018-02-08 17:58:59

标签: django optimization django-orm

型号:

class User(models.Model):
    teams = models.ManyToManyField('Team', through='TeamMember', related_name='members')

class Team(models.Model):
    pass

class TeamMember(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    position = models.CharField(max_length=255)

我正在尝试构建一个查询集,该查询集将为那些TeamMember.position包含为团队中某个字段的用户提取用户和(使用prefetch_related运行另一个查询)团队,而不会运行任何不必要的查询或连接。< / p>

这是我到目前为止的查询集:

User.objects.prefetch_related(Prefetch('teams', queryset=Team.objects.annotate(position=F('teammember__position'))))

但它正在进行不必要的加入:

SELECT `appname_user`.`id` FROM `appname_user` LIMIT 21; args=()
SELECT (`appname_teammember`.`user_id`) AS `_prefetch_related_val_user_id`, `appname_team`.`id`, `appname_teammember`.`position` AS `position` FROM `appname_team` LEFT OUTER JOIN `appname_teammember` ON (`appname_team`.`id` = `appname_teammember`.`team_id`) INNER JOIN `appname_teammember` T3 ON (`appname_team`.`id` = T3.`team_id`) WHERE T3.`user_id` IN (1); args=(1,)

当它不需要时,它会加入appname_teammember两次。任何人都知道如何消除额外的加入?

0 个答案:

没有答案