问题描述
例如,我在Django中有一个简单的一对多关系:
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.
这是我尝试过的:
def prefetch_all_team_players(self):
return self.prefetch_related(
Prefetch('team__players', to_attr='all_team_players')
)
和:
def prefetch_all_team_players(self):
return self.select_related('team').prefetch_related(
Prefetch(
'team__players',
to_attr='all_team_players'
)
)
和:
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)
)
我正在相应的管理页面上使用此功能.但是,没有按预期填充 all_team_players
.我没有任何价值. player.all_team_players.all()
没有给我任何东西.
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.
当然,替代方法是仅在需要的地方使用 player.team.players.all()
,这是可行的.但是我正在尝试通过预取来获得性能.
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?
推荐答案
我知道了-非常简单.第一和第二个预取语句就可以了.但是我访问它们的方式却不是.应该这样访问:
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
忘记先通过玩家访问团队,然后可以访问该属性.h
forgot to access the team first thru player, then the attribute is accessible. Doh
这篇关于在Django中一对多地预取行为不符合预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!