gpt4 book ai didi

python - Django select_lated 通过单个查询连接模型属性

转载 作者:行者123 更新时间:2023-12-01 03:45:00 25 4
gpt4 key购买 nike

我正在尝试通过单个查询找到最佳解决方案来检索连接模型上的属性。

我有以下模型关系:

class Player(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
season_team = models.ForeignKey(SeasonTeam, related_name='players', blank=True, null=True)
leagues = models.ManyToManyField(League, related_name='players', through='PlayerLeague')


class League(models.Model):
name = models.CharField()


class PlayerLeague(models.Model):
player = models.ForeignKey(Player)
league = models.ForeignKey(League)
stamina = models.PositiveSmallIntegerField(_('Stamina'), default=100)


class Team(models.Model):
name = models.CharField(max_length=30, validators=[
RegexValidator(regex='^[a-zA-Z0-9\s]+$', message=_('name must contain only chars and numbers'), ), ])
players = models.ManyToManyField(Player, blank=True, related_name='teams')
league = models.ForeignKey(League, related_name='teams')

这是我希望在 get_context_data 中加载的所有玩家预加载耐力属性的 View

class FormationUpdateView(AjaxResponseMixin, FormationRequirementsMixin, UpdateView):
model = Formation
template_desktop = 'hockey/formation/form.html'
template_mobile = 'hockey/formation/mobile/form.html'
form_class = FormationForm

def get_initial(self):
self.initial = {'active': True}
return self.initial.copy()

def get_context_data(self, **kwargs):
context = super(FormationUpdateView, self).get_context_data(**kwargs)
team = Team.objects.select_related('league').get(formations=self.kwargs['pk'])
context['players'] = Player.objects.filter(teams=team).all()
context['league'] = team.league
return context

def get_queryset(self):
return Formation.objects.select_related()

def get_template_names(self):
if 'Mobile' in self.request.META['HTTP_USER_AGENT']:
return self.template_mobile
return self.template_desktop

我的第一个解决方案是向 Player 类添加 stamina 方法:

def stamina(self, league):
p_l = self.leagues.through.objects.filter(league=league)[0]
return p_l.stamina

我不喜欢这个解决方案,因为它将查询每个玩家的耐力值。

感谢您的帮助

最佳答案

你的模型有点令人费解,但类似的东西应该可以最大限度地减少请求数量

from django.db.models import Q, F, Prefetch

...

def get_context_data(self, **kwargs)
context = super(FormationUpdateView, self).get_context_data(**kwargs)
team = (Team.objects
.select_related('league')
.prefetch_related(
Prefetch(
'players',
queryset=(Player.objects.filter(leagues=F('leagues'))
.prefetch_related('playerleagues'))
)
).get(formations=self.kwargs['pk']))
context['players'] = team.players.all()
context['league'] = team.league
return context

无需再次访问数据库即可获取玩家的体力。

players[0].playerleagues.all()[0].stamina

关于python - Django select_lated 通过单个查询连接模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com