Prefetch on a one-to-many in Django not behaving as expected

我怕爱的太早我们不能终老 提交于 2021-01-01 09:14:44

问题


I have a simple one-to-many relationship in Django, for example:

class Team(models.Model):

    team_mascot = models.CharField(
        max_length=200, null=True)

class Player(models.Model):

    first_name = models.CharField(max_length=200, null=True)
    last_name = models.CharField(max_length=200, null=True)

    team = models.ForeignKey(
        'players.Team',
        blank=True, null=True,
        on_delete=models.SET_NULL,
        related_name='players',
        related_query_name='player',
    )

On the Player admin page(s), I want to display some information about the Team associated with that player if the player has a team, including information about other players on that team. I want to optimize this query with a prefetch for all the related players to the current players' team. This should be fairly simple, but I can't seem to get the right prefetch.

Here's what I've tried:

def prefetch_all_team_players(self):

  return self.prefetch_related(
    Prefetch('team__players', to_attr='all_team_players')
    )

and:

def prefetch_all_team_players(self):
    return self.select_related('team').prefetch_related(
        Prefetch(
            'team__players',
            to_attr='all_team_players'
        )
    )

and:

def prefetch_all_team_players(self):
    from myproj.players.models import Team

    team_queryset = Team.objects.all()
    return self.prefetch_related(
        Prefetch('team__players', to_attr='all_team_players', queryset=team_queryset)
        )

I'm using this on the appropriate admin page. However, all_team_players is not being populated as expected. I'm not getting any value. player.all_team_players.all() doesn't give me anything.

The alternative is of course just using player.team.players.all() wherever I need it, which works. But I'm trying to gain performance with the prefetch.

Any ideas on what I'm missing here?


回答1:


I figured it out - pretty simple. The first and second prefetch statements are just fine. However the way I was accessing them was not. Should have accessed like so:

player.team.all_team_players

forgot to access the team first thru player, then the attribute is accessible. Doh



来源:https://stackoverflow.com/questions/47536903/prefetch-on-a-one-to-many-in-django-not-behaving-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!