Slide 37
Slide 37 text
SerializerͰࢦඪܭࢉ(งғؾ)
from rest_framework import serializers
from sabr.stats import Stats
from mlb.models import Batter
class BattingSerializer(serializers.HyperlinkedModelSerializer):
ba = serializers.SerializerMethodField('batting_average')
slg = serializers.SerializerMethodField('slugging')
obp = serializers.SerializerMethodField('onbase')
@classmethod
def calc_single(cls, obj):
return Stats.single(obj.h, obj.hr, obj.number_2b, obj.number_3b)
@classmethod
def calc_tb(cls, obj):
return Stats.tb(cls.calc_single(obj), obj.hr, obj.number_2b, obj.number_3b)
@classmethod
def calc_avg(cls, obj):
return Stats.avg(obj.h, obj.ab)
@classmethod
def calc_obp(cls, obj):
return Stats.obp(obj.h, obj.bb, obj.hbp, obj.ab, obj.sf)
@classmethod
def calc_slugging(cls, obj):
return Stats.slg(cls.calc_tb(obj), obj.ab)
def batting_average(self, obj):
return self.calc_avg(obj)
def slugging(self, obj):
return self.calc_slugging(obj)
def onbase(self, obj):
return self.calc_obp(obj)
class Meta:
model = Batting
fields = (
# ※͜͜ʹSerializerͷcolumn͕ฒͿ
)