Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- === modified file 'ellington/sports/models/sports.py'
- --- ellington/sports/models/sports.py 2009-11-23 21:08:16 +0000
- +++ ellington/sports/models/sports.py 2010-01-12 23:15:41 +0000
- @@ -1,14 +1,11 @@
- -from django.core import meta
- -from django.models.media import (
- - AudioClip,
- - AudioClipSet,
- - Photo,
- - Video,
- - VideoSet
- -)
- +from django.core import meta, validators
- +from django.models.media import AudioClip, AudioClipSet, Video, VideoSet
- from django.models.photogalleries import Gallery, GallerySet
- -
- -
- +from django.models import core, places
- +from django.models.alerts import lists
- +from django.models.news import Section
- +
- +import datetime
- """
- Sports are made up of sport types and sport instances. A sport type is
- @@ -25,7 +22,8 @@
- so the system will look for a module called "basketball_teams" when
- looking for teams.
- - - All individual athletes must be defined in the Player model. This allows greater flexiblity and efficiency for multi-sport athletes. Must have
- + - All individual athletes must be defined in the Player model. This allows
- + greater flexiblity and efficiency for multi-sport athletes. Must have:
- - first_name
- - last_name
- - slug
- @@ -72,18 +70,6 @@
- # - Almost all get_stats/schedule functions need to take season objects and
- # only return stats for a given season!
- -from django.core import meta, validators
- -from django.models import core, places
- -from django.core.exceptions import ObjectDoesNotExist
- -
- -from django.models import categories as categories_module
- -from django.models.alerts import lists
- -from ellington.news.parts import validators as news_validators
- -from django.models.news import Section
- -
- -
- -import datetime
- -
- #######################
- # Constants - Choices #
- #######################
- @@ -116,30 +102,33 @@
- ('ESPNU', 'ESPNU, Cox ch. 320'),
- ('MTN', 'The Mtn., Cox ch. 334'),
- ('VER', 'Versus, Cox ch. 67, HD 767'),
- - ('CBSC', 'CBS College Sports, Cox ch. 333')
- + ('CBSC', 'CBS College Sports, Cox ch. 333'),
- )
- OVERTIME_CHOICES = (
- ('OT', 'Single overtime'),
- ('OT2', 'Double overtime'),
- ('OT3', 'Triple overtime'))
- -
- +
- NOT_REQUIRED = {'blank': True, 'null': True}
- ################################
- # Generic classes (all sports) #
- ################################
- +
- class Sport(meta.Model):
- gender = meta.CharField(maxlength=1, choices=SPORT_GENDER_CHOICES)
- name = meta.CharField(maxlength=25)
- slug = meta.SlugField()
- module_prefix = meta.SlugField()
- sites = meta.ManyToManyField(core.Site)
- +
- class META:
- db_table = 'sports'
- ordering = ('name',)
- admin = meta.Admin(list_display=('id', 'name', 'slug'))
- +
- def __repr__(self):
- return self.name
- @@ -154,12 +143,16 @@
- kwargs['team__sport__id__exact'] = self.id
- if not season:
- return self.get_athlete_module().get_list(**kwargs)
- - return filter(lambda a:a.get_athlete_season_info_list(season__pk=season.id) != [], self.get_athlete_module().get_list(**kwargs))
- + return filter(lambda a: a.get_athlete_season_info_list(
- + season__pk=season.id) != [],
- + self.get_athlete_module().get_list(**kwargs))
- def get_coaches(self, season=None, **kwargs):
- if not season:
- season = self.get_current_season()
- - return filter(lambda c:c.get_coach_season_info_list(season__pk=season.id) != [], self.get_coaches_module().get_list(**kwargs))
- + return filter(lambda c: c.get_coach_season_info_list(
- + season__pk=season.id) != [],
- + self.get_coaches_module().get_list(**kwargs))
- def get_games(self, **kwargs):
- kwargs['sport__id__exact'] = self.id
- @@ -183,32 +176,43 @@
- return getattr(sports, '%s_%s' % (self.module_prefix, modtype))
- except:
- from django.models import sports_hockey
- - return getattr(sports_hockey, '%s_%s' % (self.module_prefix, modtype))
- + return getattr(
- + sports_hockey, '%s_%s' % (self.module_prefix, modtype))
- def get_current_season(self):
- """
- Get the current season of this sport
- """
- - s = self.get_season_list(start_date__lt=datetime.datetime.now(), end_date__gt=datetime.datetime.now())
- + s = self.get_season_list(
- + start_date__lt=datetime.datetime.now(),
- + end_date__gt=datetime.datetime.now())
- if len(s) == 0:
- - return self.get_season_list(start_date__lt=datetime.datetime.now())[0]
- + if self.get_season_count() >= 1:
- + return self.get_season_list()[self.get_season_count()-1]
- + else:
- + return self.get_season_list(
- + start_date__lt=datetime.datetime.now())[0]
- elif len(s) == 1:
- return s[0]
- else:
- - raise ValueError("It appears that there's no valid season for this sport!")
- + raise ValueError(
- + "It appears that there's no valid season for this sport!")
- +
- class Season(meta.Model):
- sport = meta.ForeignKey(Sport)
- - name = meta.CharField(maxlength=50, help_text="Ex: 2006, 2005-2006, Spring 2006")
- + name = meta.CharField(
- + maxlength=50, help_text="Ex: 2006, 2005-2006, Spring 2006")
- slug = meta.SlugField(prepopulate_from=('name',))
- start_date = meta.DateField()
- end_date = meta.DateField()
- +
- class META:
- ordering = ('start_date', 'end_date')
- admin = meta.Admin(
- - fields = (
- - (None, {
- - 'fields' : ('sport', 'name', 'slug', 'start_date', 'end_date'),
- + fields = ((None, {
- + 'fields': ('sport', 'name', 'slug',
- + 'start_date', 'end_date'),
- }),
- ),
- )
- @@ -220,7 +224,8 @@
- if self.start_date.year == self.end_date.year:
- return self.start_date.strftime("%Y")
- else:
- - return "%s-%s" % (self.start_date.strftime("%Y"),self.end_date.strftime("%y"))
- + return "%s-%s" % (
- + self.start_date.strftime("%Y"), self.end_date.strftime("%y"))
- def get_absolute_url(self):
- return "%s%s/" % (self.get_sport().get_absolute_url(), self.name)
- @@ -230,6 +235,7 @@
- kwargs['game_date__range'] = (self.start_date, self.end_date)
- return self.get_sport().get_games(**kwargs)
- +
- class League(meta.Model):
- sport = meta.ForeignKey(Sport)
- name = meta.CharField(maxlength=50)
- @@ -242,8 +248,7 @@
- gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
- video = meta.ForeignKey(Video, **NOT_REQUIRED)
- video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
- -
- -
- +
- class META:
- unique_together = (('slug', 'sport'),)
- ordering = ('name',)
- @@ -251,7 +256,7 @@
- admin = meta.Admin(
- fields = (
- (None, {
- - 'fields' : ('sport', 'name', 'slug'),
- + 'fields': ('sport', 'name', 'slug'),
- }),
- ),
- list_display = ('name', 'sport'),
- @@ -262,15 +267,18 @@
- return self.name
- def get_teams(self, **kwargs):
- - kwargs.update({'league__id__exact' : self.id})
- + kwargs.update({'league__id__exact': self.id})
- return self.get_sport().get_teams(**kwargs)
- def get_teams_logos(self, **kwargs):
- - kwargs.update({'league__id__exact' : self.id})
- + kwargs.update({'league__id__exact': self.id})
- teams = self.get_sport().get_teams(**kwargs)
- teamlogos = []
- for team in teams:
- - teamlogos.append({'stats': team.get_stats(season=self.get_sport().get_current_season()), 'logo': team.logo})
- + teamlogos.append(
- + {'stats': team.get_stats(
- + season=self.get_sport().get_current_season()),
- + 'logo': team.logo})
- return teamlogos
- def get_standings(self):
- @@ -292,13 +300,16 @@
- from django.core import db
- curs = db.db.cursor()
- slug = self.get_sport().module_prefix
- - query = "SELECT * FROM sports_%s_team_record WHERE league_id = %%s" % slug
- + query = "SELECT * FROM sports_%s_team_record WHERE league_id = %%s" \
- + % slug
- curs.execute(query, [self.id])
- results = list(db.dictfetchall(curs))
- - get_percent = lambda wins,losses: float(wins) / (wins + losses) if wins + losses > 0 else 0
- + get_percent = lambda wins, losses: float(wins) / (wins + losses) \
- + if wins + losses > 0 else 0
- for row in results:
- row['percent'] = get_percent(row['wins'], row['losses'])
- - row['league_percent'] = get_percent(row['league_wins'], row['league_losses'])
- + row['league_percent'] = get_percent(row['league_wins'],
- + row['league_losses'])
- return results
- def get_standings_current_season(self):
- @@ -320,13 +331,16 @@
- from django.core import db
- curs = db.db.cursor()
- slug = self.get_sport().module_prefix
- - query = "SELECT * FROM sports_%s_team_record_current WHERE league_id = %%s" % slug
- + query = """SELECT * FROM sports_%s_team_record_current
- + WHERE league_id = %%s""" % slug
- curs.execute(query, [self.id])
- results = list(db.dictfetchall(curs))
- - get_percent = lambda wins,losses: float(wins) / (wins + losses) if wins + losses > 0 else 0
- + get_percent = lambda wins, losses: float(wins) / (wins + losses) \
- + if wins + losses > 0 else 0
- for row in results:
- row['percent'] = get_percent(row['wins'], row['losses'])
- - row['league_percent'] = get_percent(row['league_wins'], row['league_losses'])
- + row['league_percent'] = get_percent(row['league_wins'],
- + row['league_losses'])
- return results
- @@ -341,16 +355,16 @@
- def get_name(self):
- if self.nick_name.strip():
- - return '%s "%s" %s' % (self.first_name, self.nick_name, self.last_name)
- + return '%s "%s" %s' % (self.first_name, self.nick_name,
- + self.last_name)
- elif self.first_name:
- return '%s %s' % (self.first_name, self.last_name)
- else:
- return self.last_name
- def __repr__(self):
- - return '%s, %s (Class of %s)' % (self.last_name, self.first_name, self.class_of)
- -
- -
- + return '%s, %s (Class of %s)' % (self.last_name, self.first_name,
- + self.class_of)
- def get_athlete_season_info(self, season=None):
- if not hasattr(self, '_athlete_season_info_%s' % hash(season)):
- @@ -367,66 +381,79 @@
- elif 'basketball' in season.get_sport().name.lower():
- season_info = self.get_basketball_athlete_season_info(
- season__slug__exact=str(season.slug))
- - setattr(self, '_athlete_season_info_%s' % hash(season), season_info)
- + setattr(self, '_athlete_season_info_%s' % hash(season),
- + season_info)
- return getattr(self, '_athlete_season_info_%s' % hash(season))
- -
- +
- def get_current_athlete_season_info(self):
- if not hasattr(self, '_current_athlete_season_info'):
- season_info_list = self.get_basketball_athlete_season_info_list()
- if len(season_info_list) == 0:
- season_info_list = self.get_football_athlete_season_info_list()
- - season_info_list = sorted(season_info_list, key=lambda x: (x.get_season().slug))
- + season_info_list = sorted(
- + season_info_list, key=lambda x: (x.get_season().slug))
- if len(season_info_list) == 0:
- return None
- - setattr(self, '_current_athlete_season_info', season_info_list[-1])
- + setattr(
- + self, '_current_athlete_season_info', season_info_list[-1])
- return getattr(self, '_current_athlete_season_info')
- -
- +
- class META:
- - admin = meta.Admin(
- - fields = (
- - (None, {
- - 'fields' : (('first_name', 'nick_name', 'last_name'), 'slug', 'birth_date', 'gender', 'class_of')
- - }),
- + admin = meta.Admin(
- + fields = (
- + (None, {'fields': (
- + ('first_name', 'nick_name', 'last_name'), 'slug',
- + 'birth_date', 'gender', 'class_of')}),
- ),
- - list_display = ('id', 'last_name', 'first_name', 'slug', 'gender', 'class_of'),
- + list_display = (
- + 'id', 'last_name', 'first_name', 'slug', 'gender', 'class_of'),
- search_fields = ('first_name', 'last_name', 'slug'),
- - ordering = ('last_name', 'first_name', 'class_of')
- - )
- + ordering = ('last_name', 'first_name', 'class_of'))
- +
- class Mvp(meta.Model):
- """
- - Set the MVPs for each week. You type in the athlete IDs each time in order for this to accept athletes from all sports.
- + Set the MVPs for each week. You type in the athlete IDs each time
- + in order for this to accept athletes from all sports.
- """
- date = meta.DateField()
- - sport = meta.ForeignKey(Season, limit_choices_to={'start_date__lt': datetime.datetime.now(), 'end_date__gte': datetime.datetime.now()})
- + sport = meta.ForeignKey(
- + Season, limit_choices_to={'start_date__lt': datetime.datetime.now(),
- + 'end_date__gte': datetime.datetime.now()})
- athlete = meta.ForeignKey(Player, core=True)
- stats = meta.TextField()
- class META:
- admin = meta.Admin()
- - ordering= ('date', )
- + ordering = ('date', )
- def _module_get_latest():
- # Do not return future mvps
- - return get_list(date__lte=datetime.date.today(), order_by=('-date', 'sports_players.last_name'), select_related=True)
- + return get_list(date__lte=datetime.date.today(),
- + order_by=('-date', 'sports_players.last_name'),
- + select_related=True)
- def __repr__(self):
- return '%s, MVP for %s' % (self.get_athlete().get_name(), self.date)
- def _manipulator_validate_athlete(self, field_data, all_data):
- - # validation to ensure that the athlete is playing in the selected season
- + # validation to ensure the athlete is playing in the selected season
- from django.core import validators
- - from django.models.sports import players, seasons, football_athletes, basketball_athletes
- + from django.models.sports \
- + import players, seasons, football_athletes, basketball_athletes
- player_obj = players.get_object(pk=field_data)
- season_obj = seasons.get_object(pk=all_data['sport'])
- try:
- - kid = season_obj.get_footballathlete(athlete__id__exact=player_obj.id)
- + kid = season_obj.get_footballathlete(
- + athlete__id__exact=player_obj.id)
- except football_athletes.FootballAthleteDoesNotExist:
- try:
- - kid = season_obj.get_basketballathlete(athlete__id__exact=player_obj.id)
- + kid = season_obj.get_basketballathlete(
- + athlete__id__exact=player_obj.id)
- except basketball_athletes.BasketballAthleteDoesNotExist:
- - raise validators.ValidationError, "%s Doesn't play in this season" % player_obj.get_name()
- + raise validators.ValidationError, \
- + "%s Doesn't play in this season" % player_obj.get_name()
- ##############
- @@ -434,9 +461,11 @@
- ##############
- """
- -Basketball methods have not been updated to reflect the Player model changes as of Oct. 5, 2007.
- +Basketball methods have not been updated to reflect the Player model changes
- +as of Oct. 5, 2007.
- """
- +
- class BasketballTeam(meta.Model):
- sport = meta.ForeignKey(Sport, limit_choices_to={'module_prefix__exact':
- 'basketball'})
- @@ -450,12 +479,13 @@
- league = meta.ForeignKey(League, blank=True, null=True,
- limit_choices_to={'sport__module_prefix__exact':
- 'basketball'})
- -
- +
- mascot = meta.CharField(maxlength=100, blank=True)
- homepage = meta.URLField(verify_exists=False, blank=True)
- head_coach = meta.CharField(maxlength=100, blank=True)
- location = meta.ForeignKey(places.City, blank=True, null=True)
- - lead_photo = meta.ImageField(blank=True, upload_to="img/sports/basketball/")
- + lead_photo = meta.ImageField(
- + blank=True, upload_to="img/sports/basketball/")
- #related objects
- audio_clip = meta.ForeignKey(AudioClip, **NOT_REQUIRED)
- audio_set = meta.ForeignKey(AudioClipSet, **NOT_REQUIRED)
- @@ -463,7 +493,7 @@
- gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
- video = meta.ForeignKey(Video, **NOT_REQUIRED)
- video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
- -
- +
- class META:
- module_name = 'basketball_teams'
- ordering = ('name',)
- @@ -472,14 +502,14 @@
- admin = meta.Admin(
- fields = (
- (None, {
- - 'fields' : ('sport', 'name', 'location', 'description',
- + 'fields': ('sport', 'name', 'location', 'description',
- 'slug', 'league', 'logo', 'mascot', 'homepage',
- 'head_coach'),
- }),
- ('Extra Info', {
- 'classes': 'collapse',
- - 'fields' : ( 'audio_clip', 'audio_set',
- - 'gallery', 'gallery_set', 'video', 'video_set'),
- + 'fields': ('audio_clip', 'audio_set', 'gallery',
- + 'gallery_set', 'video', 'video_set'),
- }),
- ),
- list_display = ('name', 'slug', 'sport', 'league'),
- @@ -488,10 +518,11 @@
- )
- def __repr__(self):
- - return "%s, %s" % (self.name,self.get_sport())
- + return "%s, %s" % (self.name, self.get_sport())
- def get_absolute_url(self):
- - return '%steams/%s/' % (self.get_sport().get_absolute_url(), self.slug)
- + return '%steams/%s/' % (
- + self.get_sport().get_absolute_url(), self.slug)
- def get_stats(self, season=None):
- """
- @@ -527,15 +558,17 @@
- """
- if not season:
- season = self.get_current_season()
- - from django.models.sports_custom_queries import sports_basketball_team_stats as query
- - query = query % { 'season' : season.id, 'in_or_eq': '=', 'team' : self.id }
- + from django.models.sports_custom_queries \
- + import sports_basketball_team_stats as query
- + query = query % {'season': season.id,
- + 'in_or_eq': '=',
- + 'team': self.id}
- from django.core import db
- curs = db.db.cursor()
- curs.execute(query)
- return db.dictfetchone(curs)
- -
- def _module_get_stats_in_bulk(idlist, season=None):
- """
- Get stats for a number of teams. Accepts a list of ids to get
- @@ -544,20 +577,27 @@
- """
- if not season:
- season = self.get_current_season()
- - from django.models.sports_custom_queries import sports_basketball_team_stats as query
- + from django.models.sports_custom_queries \
- + import sports_basketball_team_stats as query
- if len(idlist) == 0:
- return {}
- elif len(idlist) == 1:
- - query = query % { 'season' : season.id, 'in_or_eq': '=', 'team' : idlist}
- + query = query % {'season': season.id,
- + 'in_or_eq': '=',
- + 'team': idlist}
- else:
- - query = query % { 'season' : season.id, 'in_or_eq': 'IN', 'team' : tuple(idlist)}
- + query = query % {'season': season.id,
- + 'in_or_eq': 'IN',
- + 'team': tuple(idlist)}
- from django.core import db
- curs = db.db.cursor()
- curs.execute(query)
- return db.dictfetchone(curs)
- - def get_schedule(self, future_only=False, past_only=False, limit=None, order='ASC',season=None):
- + def get_schedule(
- + self, future_only=False, past_only=False, limit=None, order='ASC',
- + season=None):
- """
- Get this team's schedule.
- @@ -602,9 +642,11 @@
- else:
- limit = ''
- if season:
- - where += " AND game_date >= '%s' AND game_date <= '%s' " % (season.start_date, season.end_date)
- + where += " AND game_date >= '%s' AND game_date <= '%s' " % (
- + season.start_date, season.end_date)
- query = """SELECT * FROM sports_basketball_team_schedule
- - WHERE team_id = %%s %s ORDER BY game_date %s %s""" % (where, order, limit)
- + WHERE team_id = %%s %s
- + ORDER BY game_date %s %s""" % (where, order, limit)
- from django.core import db
- curs = db.db.cursor()
- curs.execute(query, [self.id])
- @@ -645,7 +687,9 @@
- from django.core import db
- curs = db.db.cursor()
- - query = "SELECT * FROM sports_basketball_athlete_stats WHERE team_id = %s and season_id = %s ORDER BY points_per_game DESC"
- + query = """SELECT * FROM sports_basketball_athlete_stats
- + WHERE team_id = %s and season_id = %s
- + ORDER BY points_per_game DESC"""
- args = [self.id, season.id]
- if limit:
- query += " LIMIT %s"
- @@ -653,13 +697,17 @@
- curs.execute(query, args)
- stats = list(db.dictfetchall(curs))
- for stat in stats:
- - if stat['field_goal_average'] + stat['field_goals_attempted'] + stat['field_goals_made'] > 0:
- + if stat['field_goal_average'] + stat['field_goals_attempted'] + \
- + stat['field_goals_made'] > 0:
- stat['has_field_goals'] = True
- - if stat['offensive_rebounds'] + stat['total_rebounds'] + stat['defensive_rebounds'] > 0:
- + if stat['offensive_rebounds'] + stat['total_rebounds'] + \
- + stat['defensive_rebounds'] > 0:
- stat['has_rebounds'] = True
- - if stat['three_pointers_made'] + stat['three_pointer_average'] + stat['three_pointers_attempted'] > 0:
- + if stat['three_pointers_made'] + stat['three_pointer_average'] + \
- + stat['three_pointers_attempted'] > 0:
- stat['has_three_pointers'] = True
- - if stat['free_throw_average'] + stat['free_throws_attempted'] + stat['free_throws_made'] > 0:
- + if stat['free_throw_average'] + stat['free_throws_attempted'] + \
- + stat['free_throws_made'] > 0:
- stat['has_free_throws'] = True
- stat['has_stat'] = True
- return stats
- @@ -673,12 +721,15 @@
- def get_athletes(self, season=None, **kwargs):
- if not season:
- season = self.get_sport().get_current_season()
- - return [info.get_athlete() for info in self.get_athlete_season_info_list(season__pk=season.id)]
- + return [
- + info.get_athlete() for info in self.get_athlete_season_info_list(
- + season__pk=season.id)]
- class BasketballPosition(meta.Model):
- name = meta.CharField(maxlength=30)
- abbr = meta.CharField('abbreviation', maxlength=2)
- +
- class META:
- module_name = 'basketball_positions'
- ordering = ('name',)
- @@ -758,7 +809,9 @@
- return self.get_athlete().get_name()
- def get_absolute_url(self):
- - return '%sathletes/%s/' % (self.get_season().get_sport().get_absolute_url(), self.get_athlete().slug)
- + return '%sathletes/%s/' % (
- + self.get_season().get_sport().get_absolute_url(),
- + self.get_athlete().slug)
- def get_year_in_school(self):
- """Human-readable year-in-school"""
- @@ -766,61 +819,99 @@
- def has_stats(self, season=None):
- """
- - This checks if the athlete has either a field goals. 3 pters, free throws, rebounds, if they do, we assume that they have stats
- + This checks if the athlete has field goals, 3 pters, free throws,
- + rebounds, if they do, we assume that they have stats
- """
- if not season:
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s and (field_goals_made >= 0 or field_goals_attempted >= 0 or free_throws_made >= 0 or free_throws_attempted >= 0 or three_pointers_made >= 0 or three_pointers_attempted >= 0 or points >= 0 or offensive_rebounds >= 0 or defensive_rebounds >= 0 or total_rebounds >= 0 ) ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + AND (field_goals_made >= 0 or field_goals_attempted >= 0 or
- + free_throws_made >= 0 or free_throws_attempted >= 0 or
- + three_pointers_made >= 0 or
- + three_pointers_attempted >= 0 or points >= 0 or
- + offensive_rebounds >= 0 or defensive_rebounds >= 0 or
- + total_rebounds >= 0)
- + ORDER BY game_date""", [self.id, season.id])
- return curs.rowcount > 0
- def has_field_goals(self, season=None):
- """
- - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
- + Game data is spotty: can have XX_made with or without XX_attempts.
- + Convenience function to only check one thing instead of two.
- """
- if not season:
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s and (field_goals_made >= 0 or field_goals_attempted >= 0) ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + AND (field_goals_made >= 0 or
- + field_goals_attempted >= 0)
- + ORDER BY game_date""", [self.id, season.id])
- return curs.rowcount > 0
- def has_free_throws(self, season=None):
- """
- - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
- + Game data is spotty: can have XX_made with or without XX_attempts.
- + Convenience function to only check one thing instead of two.
- """
- if not season:
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s and (free_throws_made >= 0 or free_throws_attempted >= 0 ) ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + AND (free_throws_made >= 0 or
- + free_throws_attempted >= 0)
- + ORDER BY game_date""", [self.id, season.id])
- return curs.rowcount > 0
- def has_three_pointers(self, season=None):
- """
- - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
- + Game data is spotty: can have XX_made with or without XX_attempts.
- + Convenience function to only check one thing instead of two.
- """
- if not season:
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s and (three_pointers_made >= 0 or three_pointers_attempted >= 0) ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + AND (three_pointers_made >= 0 or
- + three_pointers_attempted >= 0)
- + ORDER BY game_date""", [self.id, season.id])
- return curs.rowcount > 0
- -
- def has_rebounds(self, season=None):
- """
- - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
- + Game data is spotty: can have XX_made with or without XX_attempts.
- + Convenience function to only check one thing instead of two.
- """
- if not season:
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s and (offensive_rebounds >= 0 or defensive_rebounds >= 0 or total_rebounds >= 0 ) ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + AND (offensive_rebounds >= 0 or
- + defensive_rebounds >= 0 or
- + total_rebounds >= 0)
- + ORDER BY game_date""", [self.id, season.id])
- return curs.rowcount > 0
- -
- def get_stats(self, season=None):
- """
- Get stats for this athlete
- @@ -860,7 +951,9 @@
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_stats WHERE athlete_id = %s", [self.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_stats
- + WHERE athlete_id = %s""", [self.id])
- stats = db.dictfetchone(curs)
- if stats:
- stats['has_stats'] = self.has_stats()
- @@ -918,7 +1011,11 @@
- season = self.get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_athlete_season_stats WHERE athlete_id = %s and season_id=%s ORDER BY game_date", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_season_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + ORDER BY game_date""", [self.id, season.id])
- return list(db.dictfetchall(curs))
- def _module_get_stats_in_bulk(idlist, season=None):
- @@ -929,16 +1026,26 @@
- """
- if not season and len(idlist) >= 1:
- from django.models.sports import basketball_athletes
- - season = basketball_athletes.get_object(pk=tuple(idlist)[0]).get_season().get_sport().get_current_season()
- + season = basketball_athletes.get_object(
- + pk=tuple(
- + idlist)[0]).get_season().get_sport().get_current_season()
- from django.core import db
- curs = db.db.cursor()
- if len(idlist) == 0:
- return {}
- elif len(idlist) == 1:
- - curs.execute("SELECT * FROM sports_basketball_athlete_stats WHERE athlete_id = %s and season_id=%s ORDER BY points DESC", [idlist, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_stats
- + WHERE athlete_id = %s
- + AND season_id=%s
- + ORDER BY points DESC""", [idlist, season.id])
- else:
- - curs.execute("SELECT * FROM sports_basketball_athlete_stats WHERE athlete_id IN %s and season_id=%s ORDER BY points DESC", [tuple(idlist), season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_athlete_stats
- + WHERE athlete_id IN %s
- + AND season_id=%s
- + ORDER BY points DESC""", [tuple(idlist), season.id])
- return list(db.dictfetchall(curs))
- @@ -953,50 +1060,49 @@
- blank=True)
- favored_team = meta.ForeignKey(BasketballTeam, blank=True, null=True,
- raw_id_admin=True)
- - favored_amount = meta.FloatField(max_digits=4, decimal_places=1, blank=True,
- - null=True)
- + favored_amount = meta.FloatField(max_digits=4, decimal_places=1,
- + blank=True, null=True)
- audio_url = meta.URLField(blank=True)
- story_url = meta.URLField(blank=True)
- video_url = meta.URLField(blank=True)
- photo_url = meta.URLField(blank=True)
- expanded_box_score_url = meta.URLField(blank=True)
- top_plays_url = meta.URLField(blank=True)
- -
- +
- location = meta.ForeignKey(places.Place, blank=True, null=True,
- limit_choices_to={'place_types__slug__exact':
- 'sports_venues'})
- total_rebounds = meta.IntegerField(blank=True, null=True)
- spread = meta.SmallIntegerField(blank=True, null=True)
- is_conference_game = meta.BooleanField(default=False)
- -
- +
- special1 = meta.CharField(maxlength=255, blank=True)
- special2 = meta.CharField(maxlength=255, blank=True)
- -
- +
- class META:
- module_name = 'basketball_games'
- ordering = ('game_date', 'start_time')
- admin = meta.Admin(
- fields = (
- (None, {
- - 'fields' : ('sport', 'location', 'game_date', 'start_time',
- - 'end_time', 'tv_station', 'total_rebounds',
- - 'spread', 'is_conference_game'),
- + 'fields': ('sport', 'location', 'game_date', 'start_time',
- + 'end_time', 'tv_station', 'total_rebounds',
- + 'spread', 'is_conference_game'),
- }),
- ('Line', {
- 'classes': 'collapse',
- - 'fields' : (('favored_team', 'favored_amount'),),
- + 'fields': (('favored_team', 'favored_amount'),),
- }),
- ('Links', {
- 'classes': 'collapse',
- - 'fields' : ('audio_url', 'story_url', 'video_url',
- + 'fields': ('audio_url', 'story_url', 'video_url',
- 'photo_url', 'expanded_box_score_url',
- 'top_plays_url'),
- }),
- ('Special', {
- 'classes': 'collapse',
- 'fields': ('special1', 'special2')
- - })
- - ),
- + })),
- list_display = ('__repr__', 'sport'),
- date_hierarchy = 'game_date',
- list_filter = ('game_date', 'sport'),
- @@ -1012,12 +1118,13 @@
- return '%s: %r at %r' % (self.game_date, teams[0], teams[1])
- def get_absolute_url(self):
- - return '%sgames/%s/' % (self.get_season().get_absolute_url(), self.id)
- -
- + return '%sgames/%s/' % (
- + self.get_season().get_absolute_url(), self.id)
- +
- def _module_get_next_game_for_team_slug(slug):
- import datetime
- from django.models.sports import basketball_teams_in_games as btig
- -
- +
- now = datetime.datetime.now()
- games = btig.get_list(team__slug__exact=slug,
- game__game_date__gte=now.date(),
- @@ -1025,32 +1132,36 @@
- limit=5, select_related=True)
- # First we'll see if there are any games left today
- # that haven't started.
- - todays_games = filter(lambda x:x.get_game().game_date == now.date(),
- - games)
- + todays_games = filter(
- + lambda x: x.get_game().game_date == now.date(), games)
- if todays_games:
- - games_left_today = filter(lambda x:x.get_game().start_time > \
- - now.time(), todays_games)
- + games_left_today = filter(
- + lambda x: x.get_game().start_time > now.time(), todays_games)
- if games_left_today:
- - return sorted(games_left_today,
- - key=lambda x:x.get_game().start_time)[0].get_game()
- + return sorted(
- + games_left_today,
- + key=lambda x: x.get_game().start_time)[0].get_game()
- # No games today. Now just grab the first one
- # after today in original order.
- - remaining_games = filter(lambda x:x.get_game().game_date > now.date(),
- - games)
- + remaining_games = filter(
- + lambda x: x.get_game().game_date > now.date(), games)
- if remaining_games:
- return remaining_games[0].get_game()
- else:
- return None
- -
- +
- def has_been_played(self):
- teams = self.get_basketballteamingame_list()
- - return (self.game_date < datetime.date.today() and len(teams) == 2 and teams[0].get_score() + teams[1].get_score() > 0)
- + return (self.game_date < datetime.date.today() \
- + and len(teams) == 2 \
- + and teams[0].get_score() + teams[1].get_score() > 0)
- def get_season(self):
- from django.models.sports import seasons
- - return seasons.get_object(sport__pk = self.sport_id,
- - start_date__lte = self.game_date,
- - end_date__gte = self.game_date)
- + return seasons.get_object(
- + sport__pk = self.sport_id,
- + start_date__lte = self.game_date,
- + end_date__gte = self.game_date)
- def get_home_team(self):
- return self.get_basketballteamingame(is_home_team__exact=True)
- @@ -1143,15 +1254,21 @@
- from django.core import db
- curs = db.db.cursor()
- - curs.execute("SELECT * FROM sports_basketball_game_stats WHERE game_id = %s and season_id = %s", [self.id, season.id])
- + curs.execute(
- + """SELECT * FROM sports_basketball_game_stats
- + WHERE game_id = %s
- + AND season_id = %s""", [self.id, season.id])
- d = db.dictfetchone(curs)
- if d:
- - d['has_ot'] = d['home_score_ot'] or d['away_score_ot'] or d['home_score_2ot'] or d['away_score_2ot']
- + d['has_ot'] = d['home_score_ot'] or d['away_score_ot']\
- + or d['home_score_2ot'] or d['away_score_2ot']
- d['has_2ot'] = d['home_score_2ot'] or d['away_score_2ot']
- - d['home_team_is_winner'] = (d['home_team_score'] != 0 and
- - d['away_team_score'] != 0 and d['home_team_score'] >= d['away_team_score']) or \
- - (d['home_score_final'] != None and d['away_score_final'] != None and
- - d['home_score_final'] >= d['away_score_final'])
- + d['home_team_is_winner'] = (
- + d['home_team_score'] != 0 and d['away_team_score'] != 0\
- + and d['home_team_score'] >= d['away_team_score'])\
- + or (d['home_score_final'] != None\
- + and d['away_score_final'] != None\
- + and d['home_score_final'] >= d['away_score_final'])
- return d
- def get_athlete_stats(self, season=None):
- @@ -1204,8 +1321,11 @@
- rv[key] = list(db.dictfetchall(curs))
- return rv
- +
- class BasketballTeamInGame(meta.Model):
- - game = meta.ForeignKey(BasketballGame, edit_inline=meta.TABULAR, num_in_admin=2, min_num_in_admin=2, max_num_in_admin=2)
- + game = meta.ForeignKey(
- + BasketballGame, edit_inline=meta.TABULAR, num_in_admin=2,
- + min_num_in_admin=2, max_num_in_admin=2)
- team = meta.ForeignKey(BasketballTeam, core=True, raw_id_admin=True)
- is_home_team = meta.BooleanField('home?')
- is_winner = meta.BooleanField('winner?')
- @@ -1215,13 +1335,20 @@
- score_q4 = meta.PositiveSmallIntegerField('Q4', blank=True, null=True)
- score_ot = meta.PositiveSmallIntegerField('OT', blank=True, null=True)
- score_2ot = meta.PositiveSmallIntegerField('2OT', blank=True, null=True)
- - final_score = meta.PositiveSmallIntegerField('Final', blank=True, null=True)
- - field_goals_made = meta.PositiveSmallIntegerField('FG made', blank=True, null=True)
- - field_goals_attempted = meta.PositiveSmallIntegerField('FG att.', blank=True, null=True)
- - free_throws_made = meta.PositiveSmallIntegerField('FT made.', blank=True, null=True)
- - free_throws_attempted = meta.PositiveSmallIntegerField('FT att.', blank=True, null=True)
- - three_pointers_made = meta.PositiveSmallIntegerField('3pt made', blank=True, null=True)
- - three_pointers_attempted = meta.PositiveSmallIntegerField('3pt att.', blank=True, null=True)
- + final_score = meta.PositiveSmallIntegerField(
- + 'Final', blank=True, null=True)
- + field_goals_made = meta.PositiveSmallIntegerField(
- + 'FG made', blank=True, null=True)
- + field_goals_attempted = meta.PositiveSmallIntegerField(
- + 'FG att.', blank=True, null=True)
- + free_throws_made = meta.PositiveSmallIntegerField(
- + 'FT made.', blank=True, null=True)
- + free_throws_attempted = meta.PositiveSmallIntegerField(
- + 'FT att.', blank=True, null=True)
- + three_pointers_made = meta.PositiveSmallIntegerField(
- + '3pt made', blank=True, null=True)
- + three_pointers_attempted = meta.PositiveSmallIntegerField(
- + '3pt att.', blank=True, null=True)
- fouls = meta.PositiveSmallIntegerField(blank=True, null=True)
- turnovers = meta.PositiveSmallIntegerField(blank=True, null=True)
- assists = meta.PositiveSmallIntegerField(blank=True, null=True)
- @@ -1229,33 +1356,52 @@
- steals = meta.PositiveSmallIntegerField(blank=True, null=True)
- offensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
- defensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
- +
- class META:
- module_name = 'basketball_teams_in_games'
- ordering = ('is_home_team',)
- def __repr__(self):
- return '%s in %r' % (self.get_team().slug, self.get_game())
- -
- +
- def team_slug(self):
- return self.get_team().slug
- def get_score(self):
- if self.final_score:
- return self.final_score
- - return sum([getattr(self, 'score_%s' % sf) for sf in ('q1', 'q2', 'q3', 'q4', 'ot', '2ot') if getattr(self, 'score_%s' % sf)])
- + return sum(
- + [getattr(self, 'score_%s' % sf) for sf in (
- + 'q1', 'q2', 'q3', 'q4', 'ot', '2ot') if getattr(
- + self, 'score_%s' % sf)])
- def has_quarterly_scores(self):
- - return self.score_q1 is not None and self.score_q2 is not None and self.score_q3 is not None and self.score_q4 is not None
- + return self.score_q1 is not None\
- + and self.score_q2 is not None\
- + and self.score_q3 is not None\
- + and self.score_q4 is not None
- +
- class BasketballAthleteInGame(meta.Model):
- - game = meta.ForeignKey(BasketballGame, edit_inline=meta.TABULAR, num_in_admin=15, min_num_in_admin=15, num_extra_on_change=5)
- + game = meta.ForeignKey(
- + BasketballGame,
- + edit_inline=meta.TABULAR,
- + num_in_admin=15,
- + min_num_in_admin=15,
- + num_extra_on_change=5)
- athlete = meta.ForeignKey(BasketballAthlete, raw_id_admin=True, core=True)
- - field_goals_made = meta.PositiveSmallIntegerField('FG made', blank=True, null=True)
- - field_goals_attempted = meta.PositiveSmallIntegerField('FG att.', blank=True, null=True)
- - free_throws_made = meta.PositiveSmallIntegerField('FT made.', blank=True, null=True)
- - free_throws_attempted = meta.PositiveSmallIntegerField('FT att.', blank=True, null=True)
- - three_pointers_made = meta.PositiveSmallIntegerField('3pt made', blank=True, null=True)
- - three_pointers_attempted = meta.PositiveSmallIntegerField('3pt att.', blank=True, null=True)
- + field_goals_made = meta.PositiveSmallIntegerField(
- + 'FG made', blank=True, null=True)
- + field_goals_attempted = meta.PositiveSmallIntegerField(
- + 'FG att.', blank=True, null=True)
- + free_throws_made = meta.PositiveSmallIntegerField(
- + 'FT made.', blank=True, null=True)
- + free_throws_attempted = meta.PositiveSmallIntegerField(
- + 'FT att.', blank=True, null=True)
- + three_pointers_made = meta.PositiveSmallIntegerField(
- + '3pt made', blank=True, null=True)
- + three_pointers_attempted = meta.PositiveSmallIntegerField(
- + '3pt att.', blank=True, null=True)
- points = meta.PositiveSmallIntegerField(blank=True, null=True)
- minutes_played = meta.PositiveSmallIntegerField(blank=True, null=True)
- offensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
- @@ -1265,6 +1411,7 @@
- turnovers = meta.PositiveSmallIntegerField(blank=True, null=True)
- blocked_shots = meta.PositiveSmallIntegerField(blank=True, null=True)
- steals = meta.PositiveSmallIntegerField(blank=True, null=True)
- +
- class META:
- module_name = 'basketball_athletes_in_games'
- @@ -1284,9 +1431,11 @@
- # Football #
- ############
- +
- class FootballPosition(meta.Model):
- name = meta.CharField(maxlength=100)
- abbr = meta.CharField('abbreviation', maxlength=2)
- +
- class META:
- module_name = "football_positions"
- ordering = ('name',)
- @@ -1297,19 +1446,32 @@
- def __repr__(self):
- return self.name
- +
- class FootballTeam(meta.Model):
- - sport = meta.ForeignKey(Sport, limit_choices_to={'module_prefix__exact' : 'football'})
- + sport = meta.ForeignKey(
- + Sport, limit_choices_to={'module_prefix__exact': 'football'})
- name = meta.CharField(maxlength=50)
- description = meta.TextField()
- - logo = meta.ImageField(blank=True, upload_to="img/sports/football_team_logos")
- - school = meta.ForeignKey(places.Place,related_name='School',verbose_name="School",null=True, blank=True, raw_id_admin=True, limit_choices_to={"place_types__name__iexact" :"school" })
- - field = meta.ForeignKey(places.Place,related_name='Field',verbose_name="Field",null=True, raw_id_admin=True, blank=True, limit_choices_to={"place_types__name__iexact" :"sports venue" })
- - slug = meta.CharField('abbreviated name', maxlength=10, validator_list=[validators.isAlphaNumeric, validators.isLowerCase],
- + logo = meta.ImageField(
- + blank=True, upload_to="img/sports/football_team_logos")
- + school = meta.ForeignKey(
- + places.Place, related_name='School', verbose_name="School", null=True,
- + blank=True, raw_id_admin=True,
- + limit_choices_to={"place_types__name__iexact": "school"})
- + field = meta.ForeignKey(
- + places.Place, related_name='Field', verbose_name="Field", null=True,
- + raw_id_admin=True, blank=True,
- + limit_choices_to={"place_types__name__iexact": "sports venue"})
- + slug = meta.CharField(
- + 'abbreviated name', maxlength=10,
- + validator_list=[validators.isAlphaNumeric, validators.isLowerCase],
- help_text='This abbreviation must be unique for the sport.')
- - league = meta.ForeignKey(League, blank=True, null=True, limit_choices_to={'sport__module_prefix__exact': 'football'})
- + league = meta.ForeignKey(
- + League, blank=True, null=True,
- + limit_choices_to={'sport__module_prefix__exact': 'football'})
- alertlist = meta.ForeignKey(lists.AlertList, blank=True, null=True)
- - #validator_list=[news_validators.isValidSection]
- - section = meta.ForeignKey(Section, **NOT_REQUIRED) #default=0, core=True, blank=True
- + section = meta.ForeignKey(
- + Section, **NOT_REQUIRED) #default=0, core=True, blank=True
- homepage = meta.URLField(verify_exists=False, blank=True)
- lead_photo = meta.ImageField(blank=True, upload_to="img/sports/football/")
- #added to match basketball team for consistency
- @@ -1323,27 +1485,30 @@
- gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
- video = meta.ForeignKey(Video, **NOT_REQUIRED)
- video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
- -
- +
- class META:
- module_name = 'football_teams'
- ordering = ('name',)
- unique_together = (('slug', 'sport'),)
- has_related_links = True
- -
- +
- admin = meta.Admin(
- fields = (
- (None, {
- - 'fields' : ('sport', 'name', 'location', 'school', 'field', 'description',
- - 'slug', 'league', 'logo', 'mascot', 'homepage',
- - 'head_coach', 'section', 'alertlist'),
- + 'fields': (
- + 'sport', 'name', 'location', 'school', 'field',
- + 'description', 'slug', 'league', 'logo', 'mascot',
- + 'homepage', 'head_coach', 'section', 'alertlist'),
- }),
- ('Extra Info', {
- 'classes': 'collapse',
- - 'fields' : ( 'lead_photo', 'audio_clip', 'audio_set',
- - 'gallery', 'gallery_set', 'video', 'video_set'),
- + 'fields': (
- + 'lead_photo', 'audio_clip', 'audio_set', 'gallery',
- + 'gallery_set', 'video', 'video_set'),
- }),
- ),
- - list_display = ('id', 'name', 'slug', 'sport', 'league', 'section',),
- + list_display = (
- + 'id', 'name', 'slug', 'sport', 'league', 'section',),
- list_filter = ('sport', 'league',),
- search_fields = ('name', 'slug',),
- )
- @@ -1352,12 +1517,16 @@
- return self.name
- def get_absolute_url(self):
- - return '%steams/%s/' % (self.get_sport().get_absolute_url(), self.slug)
- + return '%steams/%s/' % (
- + self.get_sport().get_absolute_url(), self.slug)
- def get_coaches(self, season=None, **kwargs):
- if not season:
- season = self.get_sport().get_current_season()
- - return filter(lambda c:c.get_coach_season_info_list(season__pk=season.id, team__pk=self.id) != [], self.get_sport().get_coaches_module().get_list(**kwargs))
- + return filter(
- + lambda c: c.get_coach_season_info_list(
- + season__pk=season.id, team__pk=self.id) != [],
- + self.get_sport().get_coaches_module().get_list(**kwargs))
- def is_local(self):
- try:
- @@ -1400,8 +1569,9 @@
- if not season:
- season = sport.get_current_season()
- - from django.models.sports_custom_queries import football_team_stats_by_season as query
- - query = query % { 'season' : season.id, 'team' : self.id }
- + from django.models.sports_custom_queries \
- + import football_team_stats_by_season as query
- + query = query % {'season': season.id, 'team': self.id}
- from django.core import db
- curs = db.db.cursor()
- @@ -1419,12 +1589,20 @@
- if len(idlist) == 0:
- return {}
- elif len(idlist) == 1:
- - curs.execute("SELECT * FROM sports_football_team_stats_currentschedule WHERE team_id = %s ORDER BY total_points DESC", idlist)
- + curs.execute(
- + """SELECT * FROM sports_football_team_stats_currentschedule
- + WHERE team_id = %s
- + ORDER BY total_points DESC""", idlist)
- else:
- - curs.execute("SELECT * FROM sports_football_team_stats_currentschedule WHERE team_id IN %s ORDER BY total_points DESC", [tuple(idlist)])
- + curs.execute(
- + """SELECT * FROM sports_football_team_stats_currentschedule
- + WHERE team_id IN %s
- + ORDER BY total_points DESC""", [tuple(idlist)])
- return list(db.dictfetchall(curs))
- - def get_schedule(self, future_only=False, past_only=False, limit=None, order='ASC', season=None):
- + def get_schedule(
- + self, future_only=False, past_only=False, limit=None,
- + order='ASC', season=None):
- """
- Get this team's schedule.
- @@ -1472,11 +1650,15 @@
- else:
- limit = ''
- if season:
- - where += " AND game_date >= '%s' AND game_date <= '%s' " % (season.start_date, season.end_date)
- + where += " AND game_date >= '%s' AND game_date <= '%s' " \
- + % (season.start_date, season.end_date)
- # Table name changed from ellington defaults
- - query = """SELECT *
- - FROM sports_football_teams_in_games sftg, sports_football_games sfg
- - WHERE sftg.team_id = %%s and sftg.game_id = sfg.id %s ORDER BY sfg.game_date %s %s""" % (where, order, limit)
- + query = """SELECT * FROM
- + sports_football_teams_in_games sftg,
- + sports_football_games sfg
- + WHERE sftg.team_id = %%s
- + AND sftg.game_id = sfg.id %s
- + ORDER BY sfg.game_date %s %s""" % (where, order, limit)
- from django.core import db
- curs = db.db.cursor()
- @@ -1487,23 +1669,27 @@
- for x in dbdata:
- massive.append(x)
- data = massive
- - for i in range(0,len(data)):
- - data[i]['game_obj'] = football_games.get_object(pk=data[i]['game_id'])
- - data[i]['score'] = sum([data[i]['score_q2'] or 0,
- - data[i]['score_q3'] or 0,
- - data[i]['score_q1'] or 0,
- - data[i]['score_q4'] or 0,
- - data[i]['score_ot'] or 0]) or data[i]['final_score']
- - data[i]['has_been_played'] = data[i]['game_obj'].has_been_played()
- + for i in range(0, len(data)):
- + data[i]['game_obj'] = \
- + football_games.get_object(pk=data[i]['game_id'])
- + data[i]['score'] = sum(
- + [data[i]['score_q2'] or 0,
- + data[i]['score_q3'] or 0,
- + data[i]['score_q1'] or 0,
- + data[i]['score_q4'] or 0,
- + data[i]['score_ot'] or 0]) or data[i]['final_score']
- + data[i]['has_been_played'] = \
- + data[i]['game_obj'].has_been_played()
- # Should always only be one team, but just in case.
- - # Sometimes games are set without opponents, so make sure there is an opponent
- + # Sometimes games are set without opponents,
- + # so make sure there is an opponent
- from django.models.sports import football_teams_in_games
- try:
- - opponent = data[i]['game_obj'].get_footballteamingame(team__id__ne=self.id)
- + opponent = data[i]['game_obj'].get_footballteamingame(
- + team__id__ne=self.id)
- except (
- AssertionError,
- - football_teams_in_games.FootballTeamInGameDoesNotExist
- - ):
- + football_teams_in_games.FootballTeamInGameDoesNotExist):
- opponent = None
- else:
- data[i]['opponent_id'] = opponent.team_id
- @@ -1559,15 +1745,17 @@
- if not season:
- season = self.sport.get_current_season()
- - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
- + from django.models.sports_custom_queries \
- + import football_athlete_stats_by_season as query
- where = "AND team.id = %s" % self.id
- order_by = "ORDER BY points_per_game DESC"
- - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
- + query = query % {'season': season.id,
- + 'where': where, 'extra': order_by}
- from django.core import db
- curs = db.db.cursor()
- - ###TODO: Fix the limit with regex, depending on season or not
- +#TODO: Fix the limit with regex, depending on season or not
- if limit:
- query += " LIMIT %s"
- args.append(limit)
- @@ -1580,28 +1768,48 @@
- def get_athletes(self, season=None, **kwargs):
- if not season:
- season = self.get_sport().get_current_season()
- - return [info.get_athlete() for info in self.get_athlete_season_info_list(season__pk=season.id)]
- + return [
- + info.get_athlete() for info in self.get_athlete_season_info_list(
- + season__pk=season.id)]
- class FootballAthlete(meta.Model):
- - athlete = meta.ForeignKey(Player, edit_inline=meta.STACKED, related_name="football_athlete_season_info", min_num_in_admin=1, num_extra_on_change=1, max_num_in_admin=2)
- + athlete = meta.ForeignKey(
- + Player,
- + edit_inline=meta.STACKED,
- + related_name="football_athlete_season_info",
- + min_num_in_admin=1,
- + num_extra_on_change=1,
- + max_num_in_admin=2)
- season = meta.ForeignKey(Season, core=True)
- team = meta.ForeignKey(FootballTeam, related_name="athlete_season_info")
- - year_in_school = meta.CharField(maxlength=2, choices=YEAR_IN_SCHOOL_CHOICES, blank=True, null=True)
- + year_in_school = meta.CharField(
- + maxlength=2, choices=YEAR_IN_SCHOOL_CHOICES, blank=True, null=True)
- previous_school = meta.CharField(maxlength=200, blank=True)
- - height = meta.PositiveSmallIntegerField('height (inches)', blank=True, null=True)
- - weight = meta.PositiveSmallIntegerField('weight (pounds)', blank=True, null=True)
- + height = meta.PositiveSmallIntegerField(
- + 'height (inches)', blank=True, null=True)
- + weight = meta.PositiveSmallIntegerField(
- + 'weight (pounds)', blank=True, null=True)
- hometown = meta.ForeignKey(places.City, blank=True, null=True)
- - photo = meta.ImageField(blank=True, upload_to="img/sports/football_athletes")
- + photo = meta.ImageField(
- + blank=True, upload_to="img/sports/football_athletes")
- number = meta.IntegerField(blank=True, null=True)
- - primary_position = meta.ForeignKey(FootballPosition, related_name='primary_position', blank=True, null=True)
- - secondary_position = meta.ForeignKey(FootballPosition, related_name='secondary_position', blank=True, null=True)
- + primary_position = meta.ForeignKey(
- + FootballPosition, related_name='primary_position',
- + blank=True, null=True)
- + secondary_position = meta.ForeignKey(
- + FootballPosition, related_name='secondary_position',
- + blank=True, null=True)
- goal = meta.CharField(maxlength=200, blank=True)
- description = meta.TextField(blank=True)
- favorite_athlete = meta.CharField(maxlength=50, blank=True)
- superstitions = meta.CharField(maxlength=100, blank=True)
- - off_field = meta.CharField(maxlength=100, blank=True, help_text="What do you do when you aren't playing your sport?")
- - qualities = meta.CharField(maxlength=100, blank=True, help_text="What makes you unique?")
- + off_field = meta.CharField(
- + maxlength=100, blank=True,
- + help_text="What do you do when you aren't playing your sport?")
- + qualities = meta.CharField(
- + maxlength=100, blank=True,
- + help_text="What makes you unique?")
- accomplishments = meta.CharField(maxlength=200, blank=True)
- #related objects
- audio_clip = meta.ForeignKey(AudioClip, **NOT_REQUIRED)
- @@ -1620,45 +1828,51 @@
- list_filter = ('team',),
- fields = (
- (None, {
- - 'fields' : ('athlete', 'season', 'team', 'year_in_school',
- - 'number', 'height', 'weight', 'photo',
- - 'primary_position', 'secondary_position',
- - 'goal'),
- + 'fields': ('athlete', 'season', 'team', 'year_in_school',
- + 'number', 'height', 'weight', 'photo',
- + 'primary_position', 'secondary_position',
- + 'goal'),
- }),
- ('Extra Info', {
- 'classes': 'collapse',
- - 'fields' : ( 'hometown', 'description', 'favorite_athlete',
- - 'superstitions', 'off_field', 'qualities',
- - 'accomplishments', 'previous_school', 'audio_clip', 'audio_set',
- - 'gallery', 'gallery_set', 'video', 'video_set'),
- + 'fields': ('hometown', 'description', 'favorite_athlete',
- + 'superstitions', 'off_field', 'qualities',
- + 'accomplishments', 'previous_school',
- + 'audio_clip', 'audio_set', 'gallery',
- + 'gallery_set', 'video', 'video_set'),
- }),
- ),
- - search_fields = ('athlete__first_name', 'athlete__last_name', 'athlete__slug',),
- + search_fields = (
- + 'athlete__first_name',
- + 'athlete__last_name',
- + 'athlete__slug',),
- )
- module_constants = {
- - 'YEAR_IN_SCHOOL_MAP' : dict(YEAR_IN_SCHOOL_CHOICES),
- + 'YEAR_IN_SCHOOL_MAP': dict(YEAR_IN_SCHOOL_CHOICES),
- }
- def __repr__(self):
- return self.get_athlete().get_name()
- def get_absolute_url(self):
- - return '%sathletes/%s/' % (self.get_season().get_sport().get_absolute_url(), self.get_athlete().slug)
- -
- -
- + return '%sathletes/%s/' \
- + % (self.get_season().get_sport().get_absolute_url(),
- + self.get_athlete().slug)
- def has_stats(self, season):
- """
- - This checks if the athlete has either a pass attempt, rush attempt, or receptions, if they do, we assume that they have stats
- + This checks if the athlete has either a pass attempt, rush attempt,
- + or receptions, if they do, we assume that they have stats
- """
- - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
- - where = """AND athlete.id = %s
- - AND (pass_attempts > 0 or
- - rushing_attempts > 0 or
- - receptions > 0)
- - """ % self.id
- + from django.models.sports_custom_queries \
- + import football_athlete_stats_by_season as query
- + where = """
- + AND athlete.id = %s
- + AND ( pass_attempts > 0 or rushing_attempts > 0 or receptions > 0)
- + """ % self.id
- order_by = ""
- - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
- + query = query % {'season': season.id,
- + 'where': where, 'extra': order_by}
- from django.core import db
- curs = db.db.cursor()
- @@ -1713,10 +1927,12 @@
- if not season:
- season = self.get_team().get_sport().get_current_season()
- - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
- + from django.models.sports_custom_queries \
- + import football_athlete_stats_by_season as query
- where = "AND athlete.id = %s" % self.id
- order_by = ""
- - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
- + query = query % {'season': season.id,
- + 'where': where, 'extra': order_by}
- from django.core import db
- curs = db.db.cursor()
- curs.execute(query)
- @@ -1766,9 +1982,10 @@
- if not season:
- season = self.get_current_season()
- - from django.models.sports_custom_queries import football_athlete_season_stats_by_season as query
- + from django.models.sports_custom_queries \
- + import football_athlete_season_stats_by_season as query
- where = "AND athlete.id = %s" % self.id
- - query = query % { 'season' : season.id, 'where' : where }
- + query = query % {'season': season.id, 'where': where}
- from django.core import db
- curs = db.db.cursor()
- @@ -1781,9 +1998,9 @@
- stats for, and returns a list of stat dictionaries with the keys as
- described in get_stats.
- """
- -
- if season:
- - from django.models.sports_custom_queri
Add Comment
Please, Sign In to add comment