我有我用約一個團隊如何在體育聯盟進行顯示細節串行..如何在SerializerMethodFields之間共享查詢集?
class TeamLeagueSerializer(ModelSerializer):
class Meta:
model = Team
fields = [...]
games_played = fields.SerializerMethodField()
games_won = fields.SerializerMethodField()
games_lost = fields.SerializerMethodField()
points_for = fields.SerializerMethodField()
...etc...
def fixtures(self, team):
# Retrieves all relevant fixtures for a given season and a given team
return Fixture.objects.filter(Q(home_team=team) | Q(away_team=team), season=self.season)
def get_games_won(self, obj):
home_results = Q(home_team=obj, result__home_team_score__gt=F('result__away_team_score'))
away_results = Q(away_team=obj, result__away_team_score__gt=F('result__home_team_score'))
results = self.fixtures(obj).filter(home_results | away_results)
return results.count()
def get_games_lost(self, obj):
home_results = Q(home_team=obj, result__home_team_score__lt=F('result__away_team_score'))
away_results = Q(away_team=obj, result__away_team_score__lt=F('result__home_team_score'))
results = self.fixtures(obj).filter(home_results | away_results)
return results.count()
這一切工作正常,但對於8支球隊的聯賽,這可能需要大約5秒鐘以完成,因爲每個SerializerMethodField
是一個單獨的查詢正在完成..
這個代碼的非api版本更簡單與單個查詢集註釋此序列化程序試圖創建的每個屬性,而不是單個查詢。
因此,對於給定的序列化程序,是否可以做同樣的事情,並從單個查詢而不是多個構建序列化程序數據?
哦,當然了!通過試圖僅使用序列化程序而不是視圖集中的可用內容,我認真地過度複雜化了這些...我稍後再嘗試一下,並相應地接受它。 – Sayse