Guest User

Untitled

a guest
Jul 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 65.38 KB | None | 0 0
  1. === modified file 'ellington/sports/models/sports.py'
  2. --- ellington/sports/models/sports.py 2009-11-23 21:08:16 +0000
  3. +++ ellington/sports/models/sports.py 2010-01-12 23:15:41 +0000
  4. @@ -1,14 +1,11 @@
  5. -from django.core import meta
  6. -from django.models.media import (
  7. - AudioClip,
  8. - AudioClipSet,
  9. - Photo,
  10. - Video,
  11. - VideoSet
  12. -)
  13. +from django.core import meta, validators
  14. +from django.models.media import AudioClip, AudioClipSet, Video, VideoSet
  15. from django.models.photogalleries import Gallery, GallerySet
  16. -
  17. -
  18. +from django.models import core, places
  19. +from django.models.alerts import lists
  20. +from django.models.news import Section
  21. +
  22. +import datetime
  23.  
  24. """
  25. Sports are made up of sport types and sport instances. A sport type is
  26. @@ -25,7 +22,8 @@
  27. so the system will look for a module called "basketball_teams" when
  28. looking for teams.
  29.  
  30. - - All individual athletes must be defined in the Player model. This allows greater flexiblity and efficiency for multi-sport athletes. Must have
  31. + - All individual athletes must be defined in the Player model. This allows
  32. + greater flexiblity and efficiency for multi-sport athletes. Must have:
  33. - first_name
  34. - last_name
  35. - slug
  36. @@ -72,18 +70,6 @@
  37. # - Almost all get_stats/schedule functions need to take season objects and
  38. # only return stats for a given season!
  39.  
  40. -from django.core import meta, validators
  41. -from django.models import core, places
  42. -from django.core.exceptions import ObjectDoesNotExist
  43. -
  44. -from django.models import categories as categories_module
  45. -from django.models.alerts import lists
  46. -from ellington.news.parts import validators as news_validators
  47. -from django.models.news import Section
  48. -
  49. -
  50. -import datetime
  51. -
  52. #######################
  53. # Constants - Choices #
  54. #######################
  55. @@ -116,30 +102,33 @@
  56. ('ESPNU', 'ESPNU, Cox ch. 320'),
  57. ('MTN', 'The Mtn., Cox ch. 334'),
  58. ('VER', 'Versus, Cox ch. 67, HD 767'),
  59. - ('CBSC', 'CBS College Sports, Cox ch. 333')
  60. + ('CBSC', 'CBS College Sports, Cox ch. 333'),
  61. )
  62.  
  63. OVERTIME_CHOICES = (
  64. ('OT', 'Single overtime'),
  65. ('OT2', 'Double overtime'),
  66. ('OT3', 'Triple overtime'))
  67. -
  68. +
  69. NOT_REQUIRED = {'blank': True, 'null': True}
  70.  
  71. ################################
  72. # Generic classes (all sports) #
  73. ################################
  74.  
  75. +
  76. class Sport(meta.Model):
  77. gender = meta.CharField(maxlength=1, choices=SPORT_GENDER_CHOICES)
  78. name = meta.CharField(maxlength=25)
  79. slug = meta.SlugField()
  80. module_prefix = meta.SlugField()
  81. sites = meta.ManyToManyField(core.Site)
  82. +
  83. class META:
  84. db_table = 'sports'
  85. ordering = ('name',)
  86. admin = meta.Admin(list_display=('id', 'name', 'slug'))
  87. +
  88. def __repr__(self):
  89. return self.name
  90.  
  91. @@ -154,12 +143,16 @@
  92. kwargs['team__sport__id__exact'] = self.id
  93. if not season:
  94. return self.get_athlete_module().get_list(**kwargs)
  95. - return filter(lambda a:a.get_athlete_season_info_list(season__pk=season.id) != [], self.get_athlete_module().get_list(**kwargs))
  96. + return filter(lambda a: a.get_athlete_season_info_list(
  97. + season__pk=season.id) != [],
  98. + self.get_athlete_module().get_list(**kwargs))
  99.  
  100. def get_coaches(self, season=None, **kwargs):
  101. if not season:
  102. season = self.get_current_season()
  103. - return filter(lambda c:c.get_coach_season_info_list(season__pk=season.id) != [], self.get_coaches_module().get_list(**kwargs))
  104. + return filter(lambda c: c.get_coach_season_info_list(
  105. + season__pk=season.id) != [],
  106. + self.get_coaches_module().get_list(**kwargs))
  107.  
  108. def get_games(self, **kwargs):
  109. kwargs['sport__id__exact'] = self.id
  110. @@ -183,32 +176,43 @@
  111. return getattr(sports, '%s_%s' % (self.module_prefix, modtype))
  112. except:
  113. from django.models import sports_hockey
  114. - return getattr(sports_hockey, '%s_%s' % (self.module_prefix, modtype))
  115. + return getattr(
  116. + sports_hockey, '%s_%s' % (self.module_prefix, modtype))
  117.  
  118. def get_current_season(self):
  119. """
  120. Get the current season of this sport
  121. """
  122. - s = self.get_season_list(start_date__lt=datetime.datetime.now(), end_date__gt=datetime.datetime.now())
  123. + s = self.get_season_list(
  124. + start_date__lt=datetime.datetime.now(),
  125. + end_date__gt=datetime.datetime.now())
  126. if len(s) == 0:
  127. - return self.get_season_list(start_date__lt=datetime.datetime.now())[0]
  128. + if self.get_season_count() >= 1:
  129. + return self.get_season_list()[self.get_season_count()-1]
  130. + else:
  131. + return self.get_season_list(
  132. + start_date__lt=datetime.datetime.now())[0]
  133. elif len(s) == 1:
  134. return s[0]
  135. else:
  136. - raise ValueError("It appears that there's no valid season for this sport!")
  137. + raise ValueError(
  138. + "It appears that there's no valid season for this sport!")
  139. +
  140.  
  141. class Season(meta.Model):
  142. sport = meta.ForeignKey(Sport)
  143. - name = meta.CharField(maxlength=50, help_text="Ex: 2006, 2005-2006, Spring 2006")
  144. + name = meta.CharField(
  145. + maxlength=50, help_text="Ex: 2006, 2005-2006, Spring 2006")
  146. slug = meta.SlugField(prepopulate_from=('name',))
  147. start_date = meta.DateField()
  148. end_date = meta.DateField()
  149. +
  150. class META:
  151. ordering = ('start_date', 'end_date')
  152. admin = meta.Admin(
  153. - fields = (
  154. - (None, {
  155. - 'fields' : ('sport', 'name', 'slug', 'start_date', 'end_date'),
  156. + fields = ((None, {
  157. + 'fields': ('sport', 'name', 'slug',
  158. + 'start_date', 'end_date'),
  159. }),
  160. ),
  161. )
  162. @@ -220,7 +224,8 @@
  163. if self.start_date.year == self.end_date.year:
  164. return self.start_date.strftime("%Y")
  165. else:
  166. - return "%s-%s" % (self.start_date.strftime("%Y"),self.end_date.strftime("%y"))
  167. + return "%s-%s" % (
  168. + self.start_date.strftime("%Y"), self.end_date.strftime("%y"))
  169.  
  170. def get_absolute_url(self):
  171. return "%s%s/" % (self.get_sport().get_absolute_url(), self.name)
  172. @@ -230,6 +235,7 @@
  173. kwargs['game_date__range'] = (self.start_date, self.end_date)
  174. return self.get_sport().get_games(**kwargs)
  175.  
  176. +
  177. class League(meta.Model):
  178. sport = meta.ForeignKey(Sport)
  179. name = meta.CharField(maxlength=50)
  180. @@ -242,8 +248,7 @@
  181. gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
  182. video = meta.ForeignKey(Video, **NOT_REQUIRED)
  183. video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
  184. -
  185. -
  186. +
  187. class META:
  188. unique_together = (('slug', 'sport'),)
  189. ordering = ('name',)
  190. @@ -251,7 +256,7 @@
  191. admin = meta.Admin(
  192. fields = (
  193. (None, {
  194. - 'fields' : ('sport', 'name', 'slug'),
  195. + 'fields': ('sport', 'name', 'slug'),
  196. }),
  197. ),
  198. list_display = ('name', 'sport'),
  199. @@ -262,15 +267,18 @@
  200. return self.name
  201.  
  202. def get_teams(self, **kwargs):
  203. - kwargs.update({'league__id__exact' : self.id})
  204. + kwargs.update({'league__id__exact': self.id})
  205. return self.get_sport().get_teams(**kwargs)
  206.  
  207. def get_teams_logos(self, **kwargs):
  208. - kwargs.update({'league__id__exact' : self.id})
  209. + kwargs.update({'league__id__exact': self.id})
  210. teams = self.get_sport().get_teams(**kwargs)
  211. teamlogos = []
  212. for team in teams:
  213. - teamlogos.append({'stats': team.get_stats(season=self.get_sport().get_current_season()), 'logo': team.logo})
  214. + teamlogos.append(
  215. + {'stats': team.get_stats(
  216. + season=self.get_sport().get_current_season()),
  217. + 'logo': team.logo})
  218. return teamlogos
  219.  
  220. def get_standings(self):
  221. @@ -292,13 +300,16 @@
  222. from django.core import db
  223. curs = db.db.cursor()
  224. slug = self.get_sport().module_prefix
  225. - query = "SELECT * FROM sports_%s_team_record WHERE league_id = %%s" % slug
  226. + query = "SELECT * FROM sports_%s_team_record WHERE league_id = %%s" \
  227. + % slug
  228. curs.execute(query, [self.id])
  229. results = list(db.dictfetchall(curs))
  230. - get_percent = lambda wins,losses: float(wins) / (wins + losses) if wins + losses > 0 else 0
  231. + get_percent = lambda wins, losses: float(wins) / (wins + losses) \
  232. + if wins + losses > 0 else 0
  233. for row in results:
  234. row['percent'] = get_percent(row['wins'], row['losses'])
  235. - row['league_percent'] = get_percent(row['league_wins'], row['league_losses'])
  236. + row['league_percent'] = get_percent(row['league_wins'],
  237. + row['league_losses'])
  238. return results
  239.  
  240. def get_standings_current_season(self):
  241. @@ -320,13 +331,16 @@
  242. from django.core import db
  243. curs = db.db.cursor()
  244. slug = self.get_sport().module_prefix
  245. - query = "SELECT * FROM sports_%s_team_record_current WHERE league_id = %%s" % slug
  246. + query = """SELECT * FROM sports_%s_team_record_current
  247. + WHERE league_id = %%s""" % slug
  248. curs.execute(query, [self.id])
  249. results = list(db.dictfetchall(curs))
  250. - get_percent = lambda wins,losses: float(wins) / (wins + losses) if wins + losses > 0 else 0
  251. + get_percent = lambda wins, losses: float(wins) / (wins + losses) \
  252. + if wins + losses > 0 else 0
  253. for row in results:
  254. row['percent'] = get_percent(row['wins'], row['losses'])
  255. - row['league_percent'] = get_percent(row['league_wins'], row['league_losses'])
  256. + row['league_percent'] = get_percent(row['league_wins'],
  257. + row['league_losses'])
  258. return results
  259.  
  260.  
  261. @@ -341,16 +355,16 @@
  262.  
  263. def get_name(self):
  264. if self.nick_name.strip():
  265. - return '%s "%s" %s' % (self.first_name, self.nick_name, self.last_name)
  266. + return '%s "%s" %s' % (self.first_name, self.nick_name,
  267. + self.last_name)
  268. elif self.first_name:
  269. return '%s %s' % (self.first_name, self.last_name)
  270. else:
  271. return self.last_name
  272.  
  273. def __repr__(self):
  274. - return '%s, %s (Class of %s)' % (self.last_name, self.first_name, self.class_of)
  275. -
  276. -
  277. + return '%s, %s (Class of %s)' % (self.last_name, self.first_name,
  278. + self.class_of)
  279.  
  280. def get_athlete_season_info(self, season=None):
  281. if not hasattr(self, '_athlete_season_info_%s' % hash(season)):
  282. @@ -367,66 +381,79 @@
  283. elif 'basketball' in season.get_sport().name.lower():
  284. season_info = self.get_basketball_athlete_season_info(
  285. season__slug__exact=str(season.slug))
  286. - setattr(self, '_athlete_season_info_%s' % hash(season), season_info)
  287. + setattr(self, '_athlete_season_info_%s' % hash(season),
  288. + season_info)
  289. return getattr(self, '_athlete_season_info_%s' % hash(season))
  290. -
  291. +
  292. def get_current_athlete_season_info(self):
  293. if not hasattr(self, '_current_athlete_season_info'):
  294. season_info_list = self.get_basketball_athlete_season_info_list()
  295. if len(season_info_list) == 0:
  296. season_info_list = self.get_football_athlete_season_info_list()
  297. - season_info_list = sorted(season_info_list, key=lambda x: (x.get_season().slug))
  298. + season_info_list = sorted(
  299. + season_info_list, key=lambda x: (x.get_season().slug))
  300. if len(season_info_list) == 0:
  301. return None
  302. - setattr(self, '_current_athlete_season_info', season_info_list[-1])
  303. + setattr(
  304. + self, '_current_athlete_season_info', season_info_list[-1])
  305. return getattr(self, '_current_athlete_season_info')
  306. -
  307. +
  308. class META:
  309. - admin = meta.Admin(
  310. - fields = (
  311. - (None, {
  312. - 'fields' : (('first_name', 'nick_name', 'last_name'), 'slug', 'birth_date', 'gender', 'class_of')
  313. - }),
  314. + admin = meta.Admin(
  315. + fields = (
  316. + (None, {'fields': (
  317. + ('first_name', 'nick_name', 'last_name'), 'slug',
  318. + 'birth_date', 'gender', 'class_of')}),
  319. ),
  320. - list_display = ('id', 'last_name', 'first_name', 'slug', 'gender', 'class_of'),
  321. + list_display = (
  322. + 'id', 'last_name', 'first_name', 'slug', 'gender', 'class_of'),
  323. search_fields = ('first_name', 'last_name', 'slug'),
  324. - ordering = ('last_name', 'first_name', 'class_of')
  325. - )
  326. + ordering = ('last_name', 'first_name', 'class_of'))
  327. +
  328.  
  329. class Mvp(meta.Model):
  330. """
  331. - Set the MVPs for each week. You type in the athlete IDs each time in order for this to accept athletes from all sports.
  332. + Set the MVPs for each week. You type in the athlete IDs each time
  333. + in order for this to accept athletes from all sports.
  334. """
  335. date = meta.DateField()
  336. - sport = meta.ForeignKey(Season, limit_choices_to={'start_date__lt': datetime.datetime.now(), 'end_date__gte': datetime.datetime.now()})
  337. + sport = meta.ForeignKey(
  338. + Season, limit_choices_to={'start_date__lt': datetime.datetime.now(),
  339. + 'end_date__gte': datetime.datetime.now()})
  340. athlete = meta.ForeignKey(Player, core=True)
  341. stats = meta.TextField()
  342.  
  343. class META:
  344. admin = meta.Admin()
  345. - ordering= ('date', )
  346. + ordering = ('date', )
  347.  
  348. def _module_get_latest():
  349. # Do not return future mvps
  350. - return get_list(date__lte=datetime.date.today(), order_by=('-date', 'sports_players.last_name'), select_related=True)
  351. + return get_list(date__lte=datetime.date.today(),
  352. + order_by=('-date', 'sports_players.last_name'),
  353. + select_related=True)
  354.  
  355. def __repr__(self):
  356. return '%s, MVP for %s' % (self.get_athlete().get_name(), self.date)
  357.  
  358. def _manipulator_validate_athlete(self, field_data, all_data):
  359. - # validation to ensure that the athlete is playing in the selected season
  360. + # validation to ensure the athlete is playing in the selected season
  361. from django.core import validators
  362. - from django.models.sports import players, seasons, football_athletes, basketball_athletes
  363. + from django.models.sports \
  364. + import players, seasons, football_athletes, basketball_athletes
  365.  
  366. player_obj = players.get_object(pk=field_data)
  367. season_obj = seasons.get_object(pk=all_data['sport'])
  368. try:
  369. - kid = season_obj.get_footballathlete(athlete__id__exact=player_obj.id)
  370. + kid = season_obj.get_footballathlete(
  371. + athlete__id__exact=player_obj.id)
  372. except football_athletes.FootballAthleteDoesNotExist:
  373. try:
  374. - kid = season_obj.get_basketballathlete(athlete__id__exact=player_obj.id)
  375. + kid = season_obj.get_basketballathlete(
  376. + athlete__id__exact=player_obj.id)
  377. except basketball_athletes.BasketballAthleteDoesNotExist:
  378. - raise validators.ValidationError, "%s Doesn't play in this season" % player_obj.get_name()
  379. + raise validators.ValidationError, \
  380. + "%s Doesn't play in this season" % player_obj.get_name()
  381.  
  382.  
  383. ##############
  384. @@ -434,9 +461,11 @@
  385. ##############
  386.  
  387. """
  388. -Basketball methods have not been updated to reflect the Player model changes as of Oct. 5, 2007.
  389. +Basketball methods have not been updated to reflect the Player model changes
  390. +as of Oct. 5, 2007.
  391. """
  392.  
  393. +
  394. class BasketballTeam(meta.Model):
  395. sport = meta.ForeignKey(Sport, limit_choices_to={'module_prefix__exact':
  396. 'basketball'})
  397. @@ -450,12 +479,13 @@
  398. league = meta.ForeignKey(League, blank=True, null=True,
  399. limit_choices_to={'sport__module_prefix__exact':
  400. 'basketball'})
  401. -
  402. +
  403. mascot = meta.CharField(maxlength=100, blank=True)
  404. homepage = meta.URLField(verify_exists=False, blank=True)
  405. head_coach = meta.CharField(maxlength=100, blank=True)
  406. location = meta.ForeignKey(places.City, blank=True, null=True)
  407. - lead_photo = meta.ImageField(blank=True, upload_to="img/sports/basketball/")
  408. + lead_photo = meta.ImageField(
  409. + blank=True, upload_to="img/sports/basketball/")
  410. #related objects
  411. audio_clip = meta.ForeignKey(AudioClip, **NOT_REQUIRED)
  412. audio_set = meta.ForeignKey(AudioClipSet, **NOT_REQUIRED)
  413. @@ -463,7 +493,7 @@
  414. gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
  415. video = meta.ForeignKey(Video, **NOT_REQUIRED)
  416. video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
  417. -
  418. +
  419. class META:
  420. module_name = 'basketball_teams'
  421. ordering = ('name',)
  422. @@ -472,14 +502,14 @@
  423. admin = meta.Admin(
  424. fields = (
  425. (None, {
  426. - 'fields' : ('sport', 'name', 'location', 'description',
  427. + 'fields': ('sport', 'name', 'location', 'description',
  428. 'slug', 'league', 'logo', 'mascot', 'homepage',
  429. 'head_coach'),
  430. }),
  431. ('Extra Info', {
  432. 'classes': 'collapse',
  433. - 'fields' : ( 'audio_clip', 'audio_set',
  434. - 'gallery', 'gallery_set', 'video', 'video_set'),
  435. + 'fields': ('audio_clip', 'audio_set', 'gallery',
  436. + 'gallery_set', 'video', 'video_set'),
  437. }),
  438. ),
  439. list_display = ('name', 'slug', 'sport', 'league'),
  440. @@ -488,10 +518,11 @@
  441. )
  442.  
  443. def __repr__(self):
  444. - return "%s, %s" % (self.name,self.get_sport())
  445. + return "%s, %s" % (self.name, self.get_sport())
  446.  
  447. def get_absolute_url(self):
  448. - return '%steams/%s/' % (self.get_sport().get_absolute_url(), self.slug)
  449. + return '%steams/%s/' % (
  450. + self.get_sport().get_absolute_url(), self.slug)
  451.  
  452. def get_stats(self, season=None):
  453. """
  454. @@ -527,15 +558,17 @@
  455. """
  456. if not season:
  457. season = self.get_current_season()
  458. - from django.models.sports_custom_queries import sports_basketball_team_stats as query
  459. - query = query % { 'season' : season.id, 'in_or_eq': '=', 'team' : self.id }
  460. + from django.models.sports_custom_queries \
  461. + import sports_basketball_team_stats as query
  462. + query = query % {'season': season.id,
  463. + 'in_or_eq': '=',
  464. + 'team': self.id}
  465.  
  466. from django.core import db
  467. curs = db.db.cursor()
  468. curs.execute(query)
  469. return db.dictfetchone(curs)
  470.  
  471. -
  472. def _module_get_stats_in_bulk(idlist, season=None):
  473. """
  474. Get stats for a number of teams. Accepts a list of ids to get
  475. @@ -544,20 +577,27 @@
  476. """
  477. if not season:
  478. season = self.get_current_season()
  479. - from django.models.sports_custom_queries import sports_basketball_team_stats as query
  480. + from django.models.sports_custom_queries \
  481. + import sports_basketball_team_stats as query
  482. if len(idlist) == 0:
  483. return {}
  484. elif len(idlist) == 1:
  485. - query = query % { 'season' : season.id, 'in_or_eq': '=', 'team' : idlist}
  486. + query = query % {'season': season.id,
  487. + 'in_or_eq': '=',
  488. + 'team': idlist}
  489. else:
  490. - query = query % { 'season' : season.id, 'in_or_eq': 'IN', 'team' : tuple(idlist)}
  491. + query = query % {'season': season.id,
  492. + 'in_or_eq': 'IN',
  493. + 'team': tuple(idlist)}
  494.  
  495. from django.core import db
  496. curs = db.db.cursor()
  497. curs.execute(query)
  498. return db.dictfetchone(curs)
  499.  
  500. - def get_schedule(self, future_only=False, past_only=False, limit=None, order='ASC',season=None):
  501. + def get_schedule(
  502. + self, future_only=False, past_only=False, limit=None, order='ASC',
  503. + season=None):
  504. """
  505. Get this team's schedule.
  506.  
  507. @@ -602,9 +642,11 @@
  508. else:
  509. limit = ''
  510. if season:
  511. - where += " AND game_date >= '%s' AND game_date <= '%s' " % (season.start_date, season.end_date)
  512. + where += " AND game_date >= '%s' AND game_date <= '%s' " % (
  513. + season.start_date, season.end_date)
  514. query = """SELECT * FROM sports_basketball_team_schedule
  515. - WHERE team_id = %%s %s ORDER BY game_date %s %s""" % (where, order, limit)
  516. + WHERE team_id = %%s %s
  517. + ORDER BY game_date %s %s""" % (where, order, limit)
  518. from django.core import db
  519. curs = db.db.cursor()
  520. curs.execute(query, [self.id])
  521. @@ -645,7 +687,9 @@
  522.  
  523. from django.core import db
  524. curs = db.db.cursor()
  525. - query = "SELECT * FROM sports_basketball_athlete_stats WHERE team_id = %s and season_id = %s ORDER BY points_per_game DESC"
  526. + query = """SELECT * FROM sports_basketball_athlete_stats
  527. + WHERE team_id = %s and season_id = %s
  528. + ORDER BY points_per_game DESC"""
  529. args = [self.id, season.id]
  530. if limit:
  531. query += " LIMIT %s"
  532. @@ -653,13 +697,17 @@
  533. curs.execute(query, args)
  534. stats = list(db.dictfetchall(curs))
  535. for stat in stats:
  536. - if stat['field_goal_average'] + stat['field_goals_attempted'] + stat['field_goals_made'] > 0:
  537. + if stat['field_goal_average'] + stat['field_goals_attempted'] + \
  538. + stat['field_goals_made'] > 0:
  539. stat['has_field_goals'] = True
  540. - if stat['offensive_rebounds'] + stat['total_rebounds'] + stat['defensive_rebounds'] > 0:
  541. + if stat['offensive_rebounds'] + stat['total_rebounds'] + \
  542. + stat['defensive_rebounds'] > 0:
  543. stat['has_rebounds'] = True
  544. - if stat['three_pointers_made'] + stat['three_pointer_average'] + stat['three_pointers_attempted'] > 0:
  545. + if stat['three_pointers_made'] + stat['three_pointer_average'] + \
  546. + stat['three_pointers_attempted'] > 0:
  547. stat['has_three_pointers'] = True
  548. - if stat['free_throw_average'] + stat['free_throws_attempted'] + stat['free_throws_made'] > 0:
  549. + if stat['free_throw_average'] + stat['free_throws_attempted'] + \
  550. + stat['free_throws_made'] > 0:
  551. stat['has_free_throws'] = True
  552. stat['has_stat'] = True
  553. return stats
  554. @@ -673,12 +721,15 @@
  555. def get_athletes(self, season=None, **kwargs):
  556. if not season:
  557. season = self.get_sport().get_current_season()
  558. - return [info.get_athlete() for info in self.get_athlete_season_info_list(season__pk=season.id)]
  559. + return [
  560. + info.get_athlete() for info in self.get_athlete_season_info_list(
  561. + season__pk=season.id)]
  562.  
  563.  
  564. class BasketballPosition(meta.Model):
  565. name = meta.CharField(maxlength=30)
  566. abbr = meta.CharField('abbreviation', maxlength=2)
  567. +
  568. class META:
  569. module_name = 'basketball_positions'
  570. ordering = ('name',)
  571. @@ -758,7 +809,9 @@
  572. return self.get_athlete().get_name()
  573.  
  574. def get_absolute_url(self):
  575. - return '%sathletes/%s/' % (self.get_season().get_sport().get_absolute_url(), self.get_athlete().slug)
  576. + return '%sathletes/%s/' % (
  577. + self.get_season().get_sport().get_absolute_url(),
  578. + self.get_athlete().slug)
  579.  
  580. def get_year_in_school(self):
  581. """Human-readable year-in-school"""
  582. @@ -766,61 +819,99 @@
  583.  
  584. def has_stats(self, season=None):
  585. """
  586. - This checks if the athlete has either a field goals. 3 pters, free throws, rebounds, if they do, we assume that they have stats
  587. + This checks if the athlete has field goals, 3 pters, free throws,
  588. + rebounds, if they do, we assume that they have stats
  589. """
  590. if not season:
  591. season = self.get_season().get_sport().get_current_season()
  592. from django.core import db
  593. curs = db.db.cursor()
  594. - 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])
  595. + curs.execute(
  596. + """SELECT * FROM sports_basketball_athlete_season_stats
  597. + WHERE athlete_id = %s
  598. + AND season_id=%s
  599. + AND (field_goals_made >= 0 or field_goals_attempted >= 0 or
  600. + free_throws_made >= 0 or free_throws_attempted >= 0 or
  601. + three_pointers_made >= 0 or
  602. + three_pointers_attempted >= 0 or points >= 0 or
  603. + offensive_rebounds >= 0 or defensive_rebounds >= 0 or
  604. + total_rebounds >= 0)
  605. + ORDER BY game_date""", [self.id, season.id])
  606. return curs.rowcount > 0
  607.  
  608. def has_field_goals(self, season=None):
  609. """
  610. - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
  611. + Game data is spotty: can have XX_made with or without XX_attempts.
  612. + Convenience function to only check one thing instead of two.
  613. """
  614. if not season:
  615. season = self.get_season().get_sport().get_current_season()
  616. from django.core import db
  617. curs = db.db.cursor()
  618. - 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])
  619. + curs.execute(
  620. + """SELECT * FROM sports_basketball_athlete_season_stats
  621. + WHERE athlete_id = %s
  622. + AND season_id=%s
  623. + AND (field_goals_made >= 0 or
  624. + field_goals_attempted >= 0)
  625. + ORDER BY game_date""", [self.id, season.id])
  626. return curs.rowcount > 0
  627.  
  628. def has_free_throws(self, season=None):
  629. """
  630. - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
  631. + Game data is spotty: can have XX_made with or without XX_attempts.
  632. + Convenience function to only check one thing instead of two.
  633. """
  634. if not season:
  635. season = self.get_season().get_sport().get_current_season()
  636. from django.core import db
  637. curs = db.db.cursor()
  638. - 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])
  639. + curs.execute(
  640. + """SELECT * FROM sports_basketball_athlete_season_stats
  641. + WHERE athlete_id = %s
  642. + AND season_id=%s
  643. + AND (free_throws_made >= 0 or
  644. + free_throws_attempted >= 0)
  645. + ORDER BY game_date""", [self.id, season.id])
  646. return curs.rowcount > 0
  647.  
  648. def has_three_pointers(self, season=None):
  649. """
  650. - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
  651. + Game data is spotty: can have XX_made with or without XX_attempts.
  652. + Convenience function to only check one thing instead of two.
  653. """
  654. if not season:
  655. season = self.get_season().get_sport().get_current_season()
  656. from django.core import db
  657. curs = db.db.cursor()
  658. - 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])
  659. + curs.execute(
  660. + """SELECT * FROM sports_basketball_athlete_season_stats
  661. + WHERE athlete_id = %s
  662. + AND season_id=%s
  663. + AND (three_pointers_made >= 0 or
  664. + three_pointers_attempted >= 0)
  665. + ORDER BY game_date""", [self.id, season.id])
  666. return curs.rowcount > 0
  667.  
  668. -
  669. def has_rebounds(self, season=None):
  670. """
  671. - Game data is spotty: can have XX_made with or without XX_attempts. convenience function to only check one thing instead of two.
  672. + Game data is spotty: can have XX_made with or without XX_attempts.
  673. + Convenience function to only check one thing instead of two.
  674. """
  675. if not season:
  676. season = self.get_season().get_sport().get_current_season()
  677. from django.core import db
  678. curs = db.db.cursor()
  679. - 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])
  680. + curs.execute(
  681. + """SELECT * FROM sports_basketball_athlete_season_stats
  682. + WHERE athlete_id = %s
  683. + AND season_id=%s
  684. + AND (offensive_rebounds >= 0 or
  685. + defensive_rebounds >= 0 or
  686. + total_rebounds >= 0)
  687. + ORDER BY game_date""", [self.id, season.id])
  688. return curs.rowcount > 0
  689.  
  690. -
  691. def get_stats(self, season=None):
  692. """
  693. Get stats for this athlete
  694. @@ -860,7 +951,9 @@
  695.  
  696. from django.core import db
  697. curs = db.db.cursor()
  698. - curs.execute("SELECT * FROM sports_basketball_athlete_stats WHERE athlete_id = %s", [self.id])
  699. + curs.execute(
  700. + """SELECT * FROM sports_basketball_athlete_stats
  701. + WHERE athlete_id = %s""", [self.id])
  702. stats = db.dictfetchone(curs)
  703. if stats:
  704. stats['has_stats'] = self.has_stats()
  705. @@ -918,7 +1011,11 @@
  706. season = self.get_season().get_sport().get_current_season()
  707. from django.core import db
  708. curs = db.db.cursor()
  709. - 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])
  710. + curs.execute(
  711. + """SELECT * FROM sports_basketball_athlete_season_stats
  712. + WHERE athlete_id = %s
  713. + AND season_id=%s
  714. + ORDER BY game_date""", [self.id, season.id])
  715. return list(db.dictfetchall(curs))
  716.  
  717. def _module_get_stats_in_bulk(idlist, season=None):
  718. @@ -929,16 +1026,26 @@
  719. """
  720. if not season and len(idlist) >= 1:
  721. from django.models.sports import basketball_athletes
  722. - season = basketball_athletes.get_object(pk=tuple(idlist)[0]).get_season().get_sport().get_current_season()
  723. + season = basketball_athletes.get_object(
  724. + pk=tuple(
  725. + idlist)[0]).get_season().get_sport().get_current_season()
  726.  
  727. from django.core import db
  728. curs = db.db.cursor()
  729. if len(idlist) == 0:
  730. return {}
  731. elif len(idlist) == 1:
  732. - curs.execute("SELECT * FROM sports_basketball_athlete_stats WHERE athlete_id = %s and season_id=%s ORDER BY points DESC", [idlist, season.id])
  733. + curs.execute(
  734. + """SELECT * FROM sports_basketball_athlete_stats
  735. + WHERE athlete_id = %s
  736. + AND season_id=%s
  737. + ORDER BY points DESC""", [idlist, season.id])
  738. else:
  739. - 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])
  740. + curs.execute(
  741. + """SELECT * FROM sports_basketball_athlete_stats
  742. + WHERE athlete_id IN %s
  743. + AND season_id=%s
  744. + ORDER BY points DESC""", [tuple(idlist), season.id])
  745.  
  746. return list(db.dictfetchall(curs))
  747.  
  748. @@ -953,50 +1060,49 @@
  749. blank=True)
  750. favored_team = meta.ForeignKey(BasketballTeam, blank=True, null=True,
  751. raw_id_admin=True)
  752. - favored_amount = meta.FloatField(max_digits=4, decimal_places=1, blank=True,
  753. - null=True)
  754. + favored_amount = meta.FloatField(max_digits=4, decimal_places=1,
  755. + blank=True, null=True)
  756. audio_url = meta.URLField(blank=True)
  757. story_url = meta.URLField(blank=True)
  758. video_url = meta.URLField(blank=True)
  759. photo_url = meta.URLField(blank=True)
  760. expanded_box_score_url = meta.URLField(blank=True)
  761. top_plays_url = meta.URLField(blank=True)
  762. -
  763. +
  764. location = meta.ForeignKey(places.Place, blank=True, null=True,
  765. limit_choices_to={'place_types__slug__exact':
  766. 'sports_venues'})
  767. total_rebounds = meta.IntegerField(blank=True, null=True)
  768. spread = meta.SmallIntegerField(blank=True, null=True)
  769. is_conference_game = meta.BooleanField(default=False)
  770. -
  771. +
  772. special1 = meta.CharField(maxlength=255, blank=True)
  773. special2 = meta.CharField(maxlength=255, blank=True)
  774. -
  775. +
  776. class META:
  777. module_name = 'basketball_games'
  778. ordering = ('game_date', 'start_time')
  779. admin = meta.Admin(
  780. fields = (
  781. (None, {
  782. - 'fields' : ('sport', 'location', 'game_date', 'start_time',
  783. - 'end_time', 'tv_station', 'total_rebounds',
  784. - 'spread', 'is_conference_game'),
  785. + 'fields': ('sport', 'location', 'game_date', 'start_time',
  786. + 'end_time', 'tv_station', 'total_rebounds',
  787. + 'spread', 'is_conference_game'),
  788. }),
  789. ('Line', {
  790. 'classes': 'collapse',
  791. - 'fields' : (('favored_team', 'favored_amount'),),
  792. + 'fields': (('favored_team', 'favored_amount'),),
  793. }),
  794. ('Links', {
  795. 'classes': 'collapse',
  796. - 'fields' : ('audio_url', 'story_url', 'video_url',
  797. + 'fields': ('audio_url', 'story_url', 'video_url',
  798. 'photo_url', 'expanded_box_score_url',
  799. 'top_plays_url'),
  800. }),
  801. ('Special', {
  802. 'classes': 'collapse',
  803. 'fields': ('special1', 'special2')
  804. - })
  805. - ),
  806. + })),
  807. list_display = ('__repr__', 'sport'),
  808. date_hierarchy = 'game_date',
  809. list_filter = ('game_date', 'sport'),
  810. @@ -1012,12 +1118,13 @@
  811. return '%s: %r at %r' % (self.game_date, teams[0], teams[1])
  812.  
  813. def get_absolute_url(self):
  814. - return '%sgames/%s/' % (self.get_season().get_absolute_url(), self.id)
  815. -
  816. + return '%sgames/%s/' % (
  817. + self.get_season().get_absolute_url(), self.id)
  818. +
  819. def _module_get_next_game_for_team_slug(slug):
  820. import datetime
  821. from django.models.sports import basketball_teams_in_games as btig
  822. -
  823. +
  824. now = datetime.datetime.now()
  825. games = btig.get_list(team__slug__exact=slug,
  826. game__game_date__gte=now.date(),
  827. @@ -1025,32 +1132,36 @@
  828. limit=5, select_related=True)
  829. # First we'll see if there are any games left today
  830. # that haven't started.
  831. - todays_games = filter(lambda x:x.get_game().game_date == now.date(),
  832. - games)
  833. + todays_games = filter(
  834. + lambda x: x.get_game().game_date == now.date(), games)
  835. if todays_games:
  836. - games_left_today = filter(lambda x:x.get_game().start_time > \
  837. - now.time(), todays_games)
  838. + games_left_today = filter(
  839. + lambda x: x.get_game().start_time > now.time(), todays_games)
  840. if games_left_today:
  841. - return sorted(games_left_today,
  842. - key=lambda x:x.get_game().start_time)[0].get_game()
  843. + return sorted(
  844. + games_left_today,
  845. + key=lambda x: x.get_game().start_time)[0].get_game()
  846. # No games today. Now just grab the first one
  847. # after today in original order.
  848. - remaining_games = filter(lambda x:x.get_game().game_date > now.date(),
  849. - games)
  850. + remaining_games = filter(
  851. + lambda x: x.get_game().game_date > now.date(), games)
  852. if remaining_games:
  853. return remaining_games[0].get_game()
  854. else:
  855. return None
  856. -
  857. +
  858. def has_been_played(self):
  859. teams = self.get_basketballteamingame_list()
  860. - return (self.game_date < datetime.date.today() and len(teams) == 2 and teams[0].get_score() + teams[1].get_score() > 0)
  861. + return (self.game_date < datetime.date.today() \
  862. + and len(teams) == 2 \
  863. + and teams[0].get_score() + teams[1].get_score() > 0)
  864.  
  865. def get_season(self):
  866. from django.models.sports import seasons
  867. - return seasons.get_object(sport__pk = self.sport_id,
  868. - start_date__lte = self.game_date,
  869. - end_date__gte = self.game_date)
  870. + return seasons.get_object(
  871. + sport__pk = self.sport_id,
  872. + start_date__lte = self.game_date,
  873. + end_date__gte = self.game_date)
  874.  
  875. def get_home_team(self):
  876. return self.get_basketballteamingame(is_home_team__exact=True)
  877. @@ -1143,15 +1254,21 @@
  878.  
  879. from django.core import db
  880. curs = db.db.cursor()
  881. - curs.execute("SELECT * FROM sports_basketball_game_stats WHERE game_id = %s and season_id = %s", [self.id, season.id])
  882. + curs.execute(
  883. + """SELECT * FROM sports_basketball_game_stats
  884. + WHERE game_id = %s
  885. + AND season_id = %s""", [self.id, season.id])
  886. d = db.dictfetchone(curs)
  887. if d:
  888. - d['has_ot'] = d['home_score_ot'] or d['away_score_ot'] or d['home_score_2ot'] or d['away_score_2ot']
  889. + d['has_ot'] = d['home_score_ot'] or d['away_score_ot']\
  890. + or d['home_score_2ot'] or d['away_score_2ot']
  891. d['has_2ot'] = d['home_score_2ot'] or d['away_score_2ot']
  892. - d['home_team_is_winner'] = (d['home_team_score'] != 0 and
  893. - d['away_team_score'] != 0 and d['home_team_score'] >= d['away_team_score']) or \
  894. - (d['home_score_final'] != None and d['away_score_final'] != None and
  895. - d['home_score_final'] >= d['away_score_final'])
  896. + d['home_team_is_winner'] = (
  897. + d['home_team_score'] != 0 and d['away_team_score'] != 0\
  898. + and d['home_team_score'] >= d['away_team_score'])\
  899. + or (d['home_score_final'] != None\
  900. + and d['away_score_final'] != None\
  901. + and d['home_score_final'] >= d['away_score_final'])
  902. return d
  903.  
  904. def get_athlete_stats(self, season=None):
  905. @@ -1204,8 +1321,11 @@
  906. rv[key] = list(db.dictfetchall(curs))
  907. return rv
  908.  
  909. +
  910. class BasketballTeamInGame(meta.Model):
  911. - game = meta.ForeignKey(BasketballGame, edit_inline=meta.TABULAR, num_in_admin=2, min_num_in_admin=2, max_num_in_admin=2)
  912. + game = meta.ForeignKey(
  913. + BasketballGame, edit_inline=meta.TABULAR, num_in_admin=2,
  914. + min_num_in_admin=2, max_num_in_admin=2)
  915. team = meta.ForeignKey(BasketballTeam, core=True, raw_id_admin=True)
  916. is_home_team = meta.BooleanField('home?')
  917. is_winner = meta.BooleanField('winner?')
  918. @@ -1215,13 +1335,20 @@
  919. score_q4 = meta.PositiveSmallIntegerField('Q4', blank=True, null=True)
  920. score_ot = meta.PositiveSmallIntegerField('OT', blank=True, null=True)
  921. score_2ot = meta.PositiveSmallIntegerField('2OT', blank=True, null=True)
  922. - final_score = meta.PositiveSmallIntegerField('Final', blank=True, null=True)
  923. - field_goals_made = meta.PositiveSmallIntegerField('FG made', blank=True, null=True)
  924. - field_goals_attempted = meta.PositiveSmallIntegerField('FG att.', blank=True, null=True)
  925. - free_throws_made = meta.PositiveSmallIntegerField('FT made.', blank=True, null=True)
  926. - free_throws_attempted = meta.PositiveSmallIntegerField('FT att.', blank=True, null=True)
  927. - three_pointers_made = meta.PositiveSmallIntegerField('3pt made', blank=True, null=True)
  928. - three_pointers_attempted = meta.PositiveSmallIntegerField('3pt att.', blank=True, null=True)
  929. + final_score = meta.PositiveSmallIntegerField(
  930. + 'Final', blank=True, null=True)
  931. + field_goals_made = meta.PositiveSmallIntegerField(
  932. + 'FG made', blank=True, null=True)
  933. + field_goals_attempted = meta.PositiveSmallIntegerField(
  934. + 'FG att.', blank=True, null=True)
  935. + free_throws_made = meta.PositiveSmallIntegerField(
  936. + 'FT made.', blank=True, null=True)
  937. + free_throws_attempted = meta.PositiveSmallIntegerField(
  938. + 'FT att.', blank=True, null=True)
  939. + three_pointers_made = meta.PositiveSmallIntegerField(
  940. + '3pt made', blank=True, null=True)
  941. + three_pointers_attempted = meta.PositiveSmallIntegerField(
  942. + '3pt att.', blank=True, null=True)
  943. fouls = meta.PositiveSmallIntegerField(blank=True, null=True)
  944. turnovers = meta.PositiveSmallIntegerField(blank=True, null=True)
  945. assists = meta.PositiveSmallIntegerField(blank=True, null=True)
  946. @@ -1229,33 +1356,52 @@
  947. steals = meta.PositiveSmallIntegerField(blank=True, null=True)
  948. offensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
  949. defensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
  950. +
  951. class META:
  952. module_name = 'basketball_teams_in_games'
  953. ordering = ('is_home_team',)
  954.  
  955. def __repr__(self):
  956. return '%s in %r' % (self.get_team().slug, self.get_game())
  957. -
  958. +
  959. def team_slug(self):
  960. return self.get_team().slug
  961.  
  962. def get_score(self):
  963. if self.final_score:
  964. return self.final_score
  965. - return sum([getattr(self, 'score_%s' % sf) for sf in ('q1', 'q2', 'q3', 'q4', 'ot', '2ot') if getattr(self, 'score_%s' % sf)])
  966. + return sum(
  967. + [getattr(self, 'score_%s' % sf) for sf in (
  968. + 'q1', 'q2', 'q3', 'q4', 'ot', '2ot') if getattr(
  969. + self, 'score_%s' % sf)])
  970.  
  971. def has_quarterly_scores(self):
  972. - 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
  973. + return self.score_q1 is not None\
  974. + and self.score_q2 is not None\
  975. + and self.score_q3 is not None\
  976. + and self.score_q4 is not None
  977. +
  978.  
  979. class BasketballAthleteInGame(meta.Model):
  980. - game = meta.ForeignKey(BasketballGame, edit_inline=meta.TABULAR, num_in_admin=15, min_num_in_admin=15, num_extra_on_change=5)
  981. + game = meta.ForeignKey(
  982. + BasketballGame,
  983. + edit_inline=meta.TABULAR,
  984. + num_in_admin=15,
  985. + min_num_in_admin=15,
  986. + num_extra_on_change=5)
  987. athlete = meta.ForeignKey(BasketballAthlete, raw_id_admin=True, core=True)
  988. - field_goals_made = meta.PositiveSmallIntegerField('FG made', blank=True, null=True)
  989. - field_goals_attempted = meta.PositiveSmallIntegerField('FG att.', blank=True, null=True)
  990. - free_throws_made = meta.PositiveSmallIntegerField('FT made.', blank=True, null=True)
  991. - free_throws_attempted = meta.PositiveSmallIntegerField('FT att.', blank=True, null=True)
  992. - three_pointers_made = meta.PositiveSmallIntegerField('3pt made', blank=True, null=True)
  993. - three_pointers_attempted = meta.PositiveSmallIntegerField('3pt att.', blank=True, null=True)
  994. + field_goals_made = meta.PositiveSmallIntegerField(
  995. + 'FG made', blank=True, null=True)
  996. + field_goals_attempted = meta.PositiveSmallIntegerField(
  997. + 'FG att.', blank=True, null=True)
  998. + free_throws_made = meta.PositiveSmallIntegerField(
  999. + 'FT made.', blank=True, null=True)
  1000. + free_throws_attempted = meta.PositiveSmallIntegerField(
  1001. + 'FT att.', blank=True, null=True)
  1002. + three_pointers_made = meta.PositiveSmallIntegerField(
  1003. + '3pt made', blank=True, null=True)
  1004. + three_pointers_attempted = meta.PositiveSmallIntegerField(
  1005. + '3pt att.', blank=True, null=True)
  1006. points = meta.PositiveSmallIntegerField(blank=True, null=True)
  1007. minutes_played = meta.PositiveSmallIntegerField(blank=True, null=True)
  1008. offensive_rebounds = meta.PositiveSmallIntegerField(blank=True, null=True)
  1009. @@ -1265,6 +1411,7 @@
  1010. turnovers = meta.PositiveSmallIntegerField(blank=True, null=True)
  1011. blocked_shots = meta.PositiveSmallIntegerField(blank=True, null=True)
  1012. steals = meta.PositiveSmallIntegerField(blank=True, null=True)
  1013. +
  1014. class META:
  1015. module_name = 'basketball_athletes_in_games'
  1016.  
  1017. @@ -1284,9 +1431,11 @@
  1018. # Football #
  1019. ############
  1020.  
  1021. +
  1022. class FootballPosition(meta.Model):
  1023. name = meta.CharField(maxlength=100)
  1024. abbr = meta.CharField('abbreviation', maxlength=2)
  1025. +
  1026. class META:
  1027. module_name = "football_positions"
  1028. ordering = ('name',)
  1029. @@ -1297,19 +1446,32 @@
  1030. def __repr__(self):
  1031. return self.name
  1032.  
  1033. +
  1034. class FootballTeam(meta.Model):
  1035. - sport = meta.ForeignKey(Sport, limit_choices_to={'module_prefix__exact' : 'football'})
  1036. + sport = meta.ForeignKey(
  1037. + Sport, limit_choices_to={'module_prefix__exact': 'football'})
  1038. name = meta.CharField(maxlength=50)
  1039. description = meta.TextField()
  1040. - logo = meta.ImageField(blank=True, upload_to="img/sports/football_team_logos")
  1041. - 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" })
  1042. - 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" })
  1043. - slug = meta.CharField('abbreviated name', maxlength=10, validator_list=[validators.isAlphaNumeric, validators.isLowerCase],
  1044. + logo = meta.ImageField(
  1045. + blank=True, upload_to="img/sports/football_team_logos")
  1046. + school = meta.ForeignKey(
  1047. + places.Place, related_name='School', verbose_name="School", null=True,
  1048. + blank=True, raw_id_admin=True,
  1049. + limit_choices_to={"place_types__name__iexact": "school"})
  1050. + field = meta.ForeignKey(
  1051. + places.Place, related_name='Field', verbose_name="Field", null=True,
  1052. + raw_id_admin=True, blank=True,
  1053. + limit_choices_to={"place_types__name__iexact": "sports venue"})
  1054. + slug = meta.CharField(
  1055. + 'abbreviated name', maxlength=10,
  1056. + validator_list=[validators.isAlphaNumeric, validators.isLowerCase],
  1057. help_text='This abbreviation must be unique for the sport.')
  1058. - league = meta.ForeignKey(League, blank=True, null=True, limit_choices_to={'sport__module_prefix__exact': 'football'})
  1059. + league = meta.ForeignKey(
  1060. + League, blank=True, null=True,
  1061. + limit_choices_to={'sport__module_prefix__exact': 'football'})
  1062. alertlist = meta.ForeignKey(lists.AlertList, blank=True, null=True)
  1063. - #validator_list=[news_validators.isValidSection]
  1064. - section = meta.ForeignKey(Section, **NOT_REQUIRED) #default=0, core=True, blank=True
  1065. + section = meta.ForeignKey(
  1066. + Section, **NOT_REQUIRED) #default=0, core=True, blank=True
  1067. homepage = meta.URLField(verify_exists=False, blank=True)
  1068. lead_photo = meta.ImageField(blank=True, upload_to="img/sports/football/")
  1069. #added to match basketball team for consistency
  1070. @@ -1323,27 +1485,30 @@
  1071. gallery_set = meta.ForeignKey(GallerySet, **NOT_REQUIRED)
  1072. video = meta.ForeignKey(Video, **NOT_REQUIRED)
  1073. video_set = meta.ForeignKey(VideoSet, **NOT_REQUIRED)
  1074. -
  1075. +
  1076. class META:
  1077. module_name = 'football_teams'
  1078. ordering = ('name',)
  1079. unique_together = (('slug', 'sport'),)
  1080. has_related_links = True
  1081. -
  1082. +
  1083. admin = meta.Admin(
  1084. fields = (
  1085. (None, {
  1086. - 'fields' : ('sport', 'name', 'location', 'school', 'field', 'description',
  1087. - 'slug', 'league', 'logo', 'mascot', 'homepage',
  1088. - 'head_coach', 'section', 'alertlist'),
  1089. + 'fields': (
  1090. + 'sport', 'name', 'location', 'school', 'field',
  1091. + 'description', 'slug', 'league', 'logo', 'mascot',
  1092. + 'homepage', 'head_coach', 'section', 'alertlist'),
  1093. }),
  1094. ('Extra Info', {
  1095. 'classes': 'collapse',
  1096. - 'fields' : ( 'lead_photo', 'audio_clip', 'audio_set',
  1097. - 'gallery', 'gallery_set', 'video', 'video_set'),
  1098. + 'fields': (
  1099. + 'lead_photo', 'audio_clip', 'audio_set', 'gallery',
  1100. + 'gallery_set', 'video', 'video_set'),
  1101. }),
  1102. ),
  1103. - list_display = ('id', 'name', 'slug', 'sport', 'league', 'section',),
  1104. + list_display = (
  1105. + 'id', 'name', 'slug', 'sport', 'league', 'section',),
  1106. list_filter = ('sport', 'league',),
  1107. search_fields = ('name', 'slug',),
  1108. )
  1109. @@ -1352,12 +1517,16 @@
  1110. return self.name
  1111.  
  1112. def get_absolute_url(self):
  1113. - return '%steams/%s/' % (self.get_sport().get_absolute_url(), self.slug)
  1114. + return '%steams/%s/' % (
  1115. + self.get_sport().get_absolute_url(), self.slug)
  1116.  
  1117. def get_coaches(self, season=None, **kwargs):
  1118. if not season:
  1119. season = self.get_sport().get_current_season()
  1120. - 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))
  1121. + return filter(
  1122. + lambda c: c.get_coach_season_info_list(
  1123. + season__pk=season.id, team__pk=self.id) != [],
  1124. + self.get_sport().get_coaches_module().get_list(**kwargs))
  1125.  
  1126. def is_local(self):
  1127. try:
  1128. @@ -1400,8 +1569,9 @@
  1129. if not season:
  1130. season = sport.get_current_season()
  1131.  
  1132. - from django.models.sports_custom_queries import football_team_stats_by_season as query
  1133. - query = query % { 'season' : season.id, 'team' : self.id }
  1134. + from django.models.sports_custom_queries \
  1135. + import football_team_stats_by_season as query
  1136. + query = query % {'season': season.id, 'team': self.id}
  1137.  
  1138. from django.core import db
  1139. curs = db.db.cursor()
  1140. @@ -1419,12 +1589,20 @@
  1141. if len(idlist) == 0:
  1142. return {}
  1143. elif len(idlist) == 1:
  1144. - curs.execute("SELECT * FROM sports_football_team_stats_currentschedule WHERE team_id = %s ORDER BY total_points DESC", idlist)
  1145. + curs.execute(
  1146. + """SELECT * FROM sports_football_team_stats_currentschedule
  1147. + WHERE team_id = %s
  1148. + ORDER BY total_points DESC""", idlist)
  1149. else:
  1150. - curs.execute("SELECT * FROM sports_football_team_stats_currentschedule WHERE team_id IN %s ORDER BY total_points DESC", [tuple(idlist)])
  1151. + curs.execute(
  1152. + """SELECT * FROM sports_football_team_stats_currentschedule
  1153. + WHERE team_id IN %s
  1154. + ORDER BY total_points DESC""", [tuple(idlist)])
  1155. return list(db.dictfetchall(curs))
  1156.  
  1157. - def get_schedule(self, future_only=False, past_only=False, limit=None, order='ASC', season=None):
  1158. + def get_schedule(
  1159. + self, future_only=False, past_only=False, limit=None,
  1160. + order='ASC', season=None):
  1161. """
  1162. Get this team's schedule.
  1163.  
  1164. @@ -1472,11 +1650,15 @@
  1165. else:
  1166. limit = ''
  1167. if season:
  1168. - where += " AND game_date >= '%s' AND game_date <= '%s' " % (season.start_date, season.end_date)
  1169. + where += " AND game_date >= '%s' AND game_date <= '%s' " \
  1170. + % (season.start_date, season.end_date)
  1171. # Table name changed from ellington defaults
  1172. - query = """SELECT *
  1173. - FROM sports_football_teams_in_games sftg, sports_football_games sfg
  1174. - WHERE sftg.team_id = %%s and sftg.game_id = sfg.id %s ORDER BY sfg.game_date %s %s""" % (where, order, limit)
  1175. + query = """SELECT * FROM
  1176. + sports_football_teams_in_games sftg,
  1177. + sports_football_games sfg
  1178. + WHERE sftg.team_id = %%s
  1179. + AND sftg.game_id = sfg.id %s
  1180. + ORDER BY sfg.game_date %s %s""" % (where, order, limit)
  1181.  
  1182. from django.core import db
  1183. curs = db.db.cursor()
  1184. @@ -1487,23 +1669,27 @@
  1185. for x in dbdata:
  1186. massive.append(x)
  1187. data = massive
  1188. - for i in range(0,len(data)):
  1189. - data[i]['game_obj'] = football_games.get_object(pk=data[i]['game_id'])
  1190. - data[i]['score'] = sum([data[i]['score_q2'] or 0,
  1191. - data[i]['score_q3'] or 0,
  1192. - data[i]['score_q1'] or 0,
  1193. - data[i]['score_q4'] or 0,
  1194. - data[i]['score_ot'] or 0]) or data[i]['final_score']
  1195. - data[i]['has_been_played'] = data[i]['game_obj'].has_been_played()
  1196. + for i in range(0, len(data)):
  1197. + data[i]['game_obj'] = \
  1198. + football_games.get_object(pk=data[i]['game_id'])
  1199. + data[i]['score'] = sum(
  1200. + [data[i]['score_q2'] or 0,
  1201. + data[i]['score_q3'] or 0,
  1202. + data[i]['score_q1'] or 0,
  1203. + data[i]['score_q4'] or 0,
  1204. + data[i]['score_ot'] or 0]) or data[i]['final_score']
  1205. + data[i]['has_been_played'] = \
  1206. + data[i]['game_obj'].has_been_played()
  1207. # Should always only be one team, but just in case.
  1208. - # Sometimes games are set without opponents, so make sure there is an opponent
  1209. + # Sometimes games are set without opponents,
  1210. + # so make sure there is an opponent
  1211. from django.models.sports import football_teams_in_games
  1212. try:
  1213. - opponent = data[i]['game_obj'].get_footballteamingame(team__id__ne=self.id)
  1214. + opponent = data[i]['game_obj'].get_footballteamingame(
  1215. + team__id__ne=self.id)
  1216. except (
  1217. AssertionError,
  1218. - football_teams_in_games.FootballTeamInGameDoesNotExist
  1219. - ):
  1220. + football_teams_in_games.FootballTeamInGameDoesNotExist):
  1221. opponent = None
  1222. else:
  1223. data[i]['opponent_id'] = opponent.team_id
  1224. @@ -1559,15 +1745,17 @@
  1225. if not season:
  1226. season = self.sport.get_current_season()
  1227.  
  1228. - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
  1229. + from django.models.sports_custom_queries \
  1230. + import football_athlete_stats_by_season as query
  1231. where = "AND team.id = %s" % self.id
  1232. order_by = "ORDER BY points_per_game DESC"
  1233. - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
  1234. + query = query % {'season': season.id,
  1235. + 'where': where, 'extra': order_by}
  1236.  
  1237. from django.core import db
  1238. curs = db.db.cursor()
  1239.  
  1240. - ###TODO: Fix the limit with regex, depending on season or not
  1241. +#TODO: Fix the limit with regex, depending on season or not
  1242. if limit:
  1243. query += " LIMIT %s"
  1244. args.append(limit)
  1245. @@ -1580,28 +1768,48 @@
  1246. def get_athletes(self, season=None, **kwargs):
  1247. if not season:
  1248. season = self.get_sport().get_current_season()
  1249. - return [info.get_athlete() for info in self.get_athlete_season_info_list(season__pk=season.id)]
  1250. + return [
  1251. + info.get_athlete() for info in self.get_athlete_season_info_list(
  1252. + season__pk=season.id)]
  1253.  
  1254.  
  1255. class FootballAthlete(meta.Model):
  1256. - 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)
  1257. + athlete = meta.ForeignKey(
  1258. + Player,
  1259. + edit_inline=meta.STACKED,
  1260. + related_name="football_athlete_season_info",
  1261. + min_num_in_admin=1,
  1262. + num_extra_on_change=1,
  1263. + max_num_in_admin=2)
  1264. season = meta.ForeignKey(Season, core=True)
  1265. team = meta.ForeignKey(FootballTeam, related_name="athlete_season_info")
  1266. - year_in_school = meta.CharField(maxlength=2, choices=YEAR_IN_SCHOOL_CHOICES, blank=True, null=True)
  1267. + year_in_school = meta.CharField(
  1268. + maxlength=2, choices=YEAR_IN_SCHOOL_CHOICES, blank=True, null=True)
  1269. previous_school = meta.CharField(maxlength=200, blank=True)
  1270. - height = meta.PositiveSmallIntegerField('height (inches)', blank=True, null=True)
  1271. - weight = meta.PositiveSmallIntegerField('weight (pounds)', blank=True, null=True)
  1272. + height = meta.PositiveSmallIntegerField(
  1273. + 'height (inches)', blank=True, null=True)
  1274. + weight = meta.PositiveSmallIntegerField(
  1275. + 'weight (pounds)', blank=True, null=True)
  1276. hometown = meta.ForeignKey(places.City, blank=True, null=True)
  1277. - photo = meta.ImageField(blank=True, upload_to="img/sports/football_athletes")
  1278. + photo = meta.ImageField(
  1279. + blank=True, upload_to="img/sports/football_athletes")
  1280. number = meta.IntegerField(blank=True, null=True)
  1281. - primary_position = meta.ForeignKey(FootballPosition, related_name='primary_position', blank=True, null=True)
  1282. - secondary_position = meta.ForeignKey(FootballPosition, related_name='secondary_position', blank=True, null=True)
  1283. + primary_position = meta.ForeignKey(
  1284. + FootballPosition, related_name='primary_position',
  1285. + blank=True, null=True)
  1286. + secondary_position = meta.ForeignKey(
  1287. + FootballPosition, related_name='secondary_position',
  1288. + blank=True, null=True)
  1289. goal = meta.CharField(maxlength=200, blank=True)
  1290. description = meta.TextField(blank=True)
  1291. favorite_athlete = meta.CharField(maxlength=50, blank=True)
  1292. superstitions = meta.CharField(maxlength=100, blank=True)
  1293. - off_field = meta.CharField(maxlength=100, blank=True, help_text="What do you do when you aren't playing your sport?")
  1294. - qualities = meta.CharField(maxlength=100, blank=True, help_text="What makes you unique?")
  1295. + off_field = meta.CharField(
  1296. + maxlength=100, blank=True,
  1297. + help_text="What do you do when you aren't playing your sport?")
  1298. + qualities = meta.CharField(
  1299. + maxlength=100, blank=True,
  1300. + help_text="What makes you unique?")
  1301. accomplishments = meta.CharField(maxlength=200, blank=True)
  1302. #related objects
  1303. audio_clip = meta.ForeignKey(AudioClip, **NOT_REQUIRED)
  1304. @@ -1620,45 +1828,51 @@
  1305. list_filter = ('team',),
  1306. fields = (
  1307. (None, {
  1308. - 'fields' : ('athlete', 'season', 'team', 'year_in_school',
  1309. - 'number', 'height', 'weight', 'photo',
  1310. - 'primary_position', 'secondary_position',
  1311. - 'goal'),
  1312. + 'fields': ('athlete', 'season', 'team', 'year_in_school',
  1313. + 'number', 'height', 'weight', 'photo',
  1314. + 'primary_position', 'secondary_position',
  1315. + 'goal'),
  1316. }),
  1317. ('Extra Info', {
  1318. 'classes': 'collapse',
  1319. - 'fields' : ( 'hometown', 'description', 'favorite_athlete',
  1320. - 'superstitions', 'off_field', 'qualities',
  1321. - 'accomplishments', 'previous_school', 'audio_clip', 'audio_set',
  1322. - 'gallery', 'gallery_set', 'video', 'video_set'),
  1323. + 'fields': ('hometown', 'description', 'favorite_athlete',
  1324. + 'superstitions', 'off_field', 'qualities',
  1325. + 'accomplishments', 'previous_school',
  1326. + 'audio_clip', 'audio_set', 'gallery',
  1327. + 'gallery_set', 'video', 'video_set'),
  1328. }),
  1329. ),
  1330. - search_fields = ('athlete__first_name', 'athlete__last_name', 'athlete__slug',),
  1331. + search_fields = (
  1332. + 'athlete__first_name',
  1333. + 'athlete__last_name',
  1334. + 'athlete__slug',),
  1335. )
  1336. module_constants = {
  1337. - 'YEAR_IN_SCHOOL_MAP' : dict(YEAR_IN_SCHOOL_CHOICES),
  1338. + 'YEAR_IN_SCHOOL_MAP': dict(YEAR_IN_SCHOOL_CHOICES),
  1339. }
  1340.  
  1341. def __repr__(self):
  1342. return self.get_athlete().get_name()
  1343.  
  1344. def get_absolute_url(self):
  1345. - return '%sathletes/%s/' % (self.get_season().get_sport().get_absolute_url(), self.get_athlete().slug)
  1346. -
  1347. -
  1348. + return '%sathletes/%s/' \
  1349. + % (self.get_season().get_sport().get_absolute_url(),
  1350. + self.get_athlete().slug)
  1351.  
  1352. def has_stats(self, season):
  1353. """
  1354. - This checks if the athlete has either a pass attempt, rush attempt, or receptions, if they do, we assume that they have stats
  1355. + This checks if the athlete has either a pass attempt, rush attempt,
  1356. + or receptions, if they do, we assume that they have stats
  1357. """
  1358. - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
  1359. - where = """AND athlete.id = %s
  1360. - AND (pass_attempts > 0 or
  1361. - rushing_attempts > 0 or
  1362. - receptions > 0)
  1363. - """ % self.id
  1364. + from django.models.sports_custom_queries \
  1365. + import football_athlete_stats_by_season as query
  1366. + where = """
  1367. + AND athlete.id = %s
  1368. + AND ( pass_attempts > 0 or rushing_attempts > 0 or receptions > 0)
  1369. + """ % self.id
  1370. order_by = ""
  1371. - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
  1372. + query = query % {'season': season.id,
  1373. + 'where': where, 'extra': order_by}
  1374.  
  1375. from django.core import db
  1376. curs = db.db.cursor()
  1377. @@ -1713,10 +1927,12 @@
  1378. if not season:
  1379. season = self.get_team().get_sport().get_current_season()
  1380.  
  1381. - from django.models.sports_custom_queries import football_athlete_stats_by_season as query
  1382. + from django.models.sports_custom_queries \
  1383. + import football_athlete_stats_by_season as query
  1384. where = "AND athlete.id = %s" % self.id
  1385. order_by = ""
  1386. - query = query % { 'season' : season.id, 'where' : where, 'extra' : order_by }
  1387. + query = query % {'season': season.id,
  1388. + 'where': where, 'extra': order_by}
  1389. from django.core import db
  1390. curs = db.db.cursor()
  1391. curs.execute(query)
  1392. @@ -1766,9 +1982,10 @@
  1393. if not season:
  1394. season = self.get_current_season()
  1395.  
  1396. - from django.models.sports_custom_queries import football_athlete_season_stats_by_season as query
  1397. + from django.models.sports_custom_queries \
  1398. + import football_athlete_season_stats_by_season as query
  1399. where = "AND athlete.id = %s" % self.id
  1400. - query = query % { 'season' : season.id, 'where' : where }
  1401. + query = query % {'season': season.id, 'where': where}
  1402.  
  1403. from django.core import db
  1404. curs = db.db.cursor()
  1405. @@ -1781,9 +1998,9 @@
  1406. stats for, and returns a list of stat dictionaries with the keys as
  1407. described in get_stats.
  1408. """
  1409. -
  1410. if season:
  1411. - from django.models.sports_custom_queri
Add Comment
Please, Sign In to add comment