如何在预取内的anateate()中访问queryset的字段?

时间:2018-10-14 23:09:48

标签: django

class PlayerProfile(models.Model):
    nickname = models.CharField(max_length=255)

class Team(models.Model):
    players = models.ManyToManyField(PlayerProfile, blank=True, related_name='teams')
    captain = models.ForeignKey(PlayerProfile, null=True, on_delete=models.SET_NULL)

class TeamView(viewsets.ModelViewSet):
   ...
    def get_queryset(self):
        queryset = Team.objects.all()
        queryset = queryset.prefetch_related(
            Prefetch(
                'players',
                queryset=PlayerProfile.objects.annotate(is_captain=F('?'))
            ))
        return queryset

queryset=PlayerProfile.objects.annotate(is_captain=F('?'))行上,我基本上想基于is_captain对象的队长字段向每个玩家注释字段Team是对还是错。

这可能吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

queryset = queryset.prefetch_related(
    Prefetch(
        'players',
      queryset=PlayerProfile.objects.annotate(is_captain=F(teams__captain))
    ))

答案 1 :(得分:0)

针对同样问题的任何人。

queryset = queryset.prefetch_related(
Prefetch(
    'players',
    queryset=PlayerProfile.objects.annotate(
        is_captain=Exists(Team.objects.filter(captain=OuterRef('id')))
    )
))