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
是对还是错。
这可能吗?
答案 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')))
)
))