def ajax_get_related_models(request): model_name = request.GET.get('model') svg_nodes = [] svg_links = [] # Temp for now: cur_group_count = 1 model = get_model(middle=model_name) log.debug(("Getting related models for ", model)) related_models = [ rel for rel in model.get_related_models(app_names=["nba_stats"]) ] fields = {} groups_dict = {} for rel_model in related_models: # Note: This only grabs the first parent defined in models.py. # Because of this, I'm not sure it works in 100% of cases right now. # Additionally, it forces us to be careful with our model definitions parent_model = rel_model.__base__ log.debug(("ZEBRA", rel_model, parent_model)) fields[rel_model.__name__] = get_user_exposed_model_fields(rel_model) if parent_model not in groups_dict: log.debug((parent_model, " not in groups dict yet. adding it as group no. ", cur_group_count)) groups_dict[parent_model] = cur_group_count if parent_model != UserExposedModel: svg_nodes.append({ 'id': parent_model.__name__, 'group': cur_group_count }) svg_links.append({ 'source': parent_model.__name__, 'target': model_name, 'value': 3 }) cur_group_count += 1 group = groups_dict[parent_model] svg_nodes.append({'id': rel_model.__name__, 'group': group}) if parent_model != UserExposedModel: svg_links.append({ 'source': rel_model.__name__, 'target': parent_model.__name__, 'value': 2 }) related_models = [rel.__name__ for rel in related_models] data = { 'related': related_models, 'fields': fields, 'nodes': svg_nodes, 'links': svg_links } return JsonResponse(data)
def ajax_send_user_query(request): primary_model_name = request.GET.get('primary_model_name') model = get_model(middle=primary_model_name) filters = simplejson.loads(request.GET.get('filters_list')) filter_dict = {} for user_qry in filters: table_field = user_qry['table_field'].lower() log.debug(table_field) table, field = table_field.split("__") if table != model.__name__.lower(): field = table_field operator = user_qry['operator'] input_val = user_qry['input_val'] final_field = field + "__" + operator filter_dict[final_field] = input_val raw_fields_str = request.GET.get('fields_wanted') fields_wanted = raw_fields_str.lstrip("[").rstrip("]").replace( '"', "").split(",") serialize_fields = [] for field in fields_wanted: log.debug(("field wanted ", field)) table, sub_field = [x.lower() for x in field.split("__")] if table == model.__name__.lower(): field_to_add = sub_field else: field_to_add = field.lower() log.debug(("field as it is being add ", field_to_add)) serialize_fields.append(field_to_add.lower()) qry_result = model.objects.filter(**filter_dict).values(*serialize_fields) results_list = [] for result in qry_result: ordered_result_dict = OrderedDict() for field in serialize_fields: val = str(result[field]) if isinstance(result[field], date) else result[field] ordered_result_dict[field] = val results_list.append(ordered_result_dict) data = simplejson.dumps(results_list) request.session['user_query_data'] = data return JsonResponse(data, safe=False)
def _get_objects(self, detail_flag=False): log.debug("in _get objects") log.debug(("len(self.raw_data): ", len(self.raw_data))) objects = [] idx = 1 if detail_flag else 0 rawdata = self.raw_data[idx] parms = rawdata['parameters'] measure_type = parms['MeasureType'] on = rawdata['resultSets'][1] off = rawdata['resultSets'][2] rows = on['rowSet'] + off['rowSet'] headers = on['headers'] prefix = "Player" middle = measure_type.replace(" ", "") if detail_flag else "" suffix = "OnOffDetail" if detail_flag else "OnOffSummary" model = get_model(prefix, middle, suffix) for row in rows: data = dict(zip(headers, row)) data['SEASON_ID'] = make_season_int(parms['Season']) data['MEASURE_TYPE'] = parms['MeasureType'] data['SEASON_TYPE'] = parms['SeasonType'] data['PER_MODE'] = parms['PerMode'] data['TEAM'] = Team.objects.get(team_id=data['TEAM_ID']) data['PLAYER'] = Player.objects.get(player_id=data['VS_PLAYER_ID']) if detail_flag: if measure_type == "Misc": data['PTS_SECOND_CHANCE'] = data['PTS_2ND_CHANCE'] data['OPP_PTS_SECOND_CHANCE'] = data['OPP_PTS_2ND_CHANCE'] elif measure_type == "Scoring": data['PCT_PTS_2PT_MIDRANGE'] = data['PCT_PTS_2PT_MR'] final_data = auto_strip_and_convert_fields(model, data, uppercase=True, make_instance=False) filter_dict = make_unique_filter_dict(model, final_data) obj, created = model.objects.update_or_create(**filter_dict, defaults=final_data) if created: log.debug(("Created new OnOff ", filter_dict)) objects.append(obj) return objects
def fetch_raw_data(self, season=None, measure_type="Base", per_mode=TOTALS, season_type=REGULAR_SEASON, group_quantity=5): self.measure_type = measure_type self.model = get_model(prefix=self.measure_type, suffix="Lineup") self.raw_data = [] if measure_type in [USAGE, DEFENSE]: raise ValueError("Usage is not a valid measure type for lineups.") if season is None: season = make_season_str(determine_season_for_date(date.today())) log.debug(("Fetching data", season, season_type, measure_type, per_mode, group_quantity)) # Really hope this respects season type. I've seen scenarios where it doesn't lineup = Lineups(season=str(season), season_type=season_type, per_mode=per_mode, group_quantity=group_quantity, measure_type=measure_type) resp_json = lineup.json parms = resp_json['parameters'] result_set = resp_json['resultSets'][0] lineup_rows = dictify(result_set) for row in lineup_rows: row['TEAM'] = Team.objects.get(team_id=int(row['TEAM_ID'])) row['SEASON_ID'] = make_season_int(parms['Season']) row['MEASURE_TYPE'] = parms['MeasureType'] row['SEASON_TYPE'] = parms['SeasonType'] row['PER_MODE'] = parms['PerMode'] row['GROUP_QUANTITY'] = parms['GroupQuantity'] row['SEASON'] = season if measure_type == "Misc": row['PTS_SECOND_CHANCE'] = row['PTS_2ND_CHANCE'] row['OPP_PTS_SECOND_CHANCE'] = row['OPP_PTS_2ND_CHANCE'] elif measure_type == "Scoring": row['PCT_PTS_2PT_MIDRANGE'] = row['PCT_PTS_2PT_MR'] proc_row = convert_dict_keys_to_lowercase(row) self.raw_data.append(proc_row)
def splits(self): prefix = "Player" if self.player_or_team == PlayerStats else "Team" model = get_model(prefix=prefix, middle=self.measure_type.replace( "Base", "Traditional"), suffix="Split") splits = [] for row in self.raw_data: data = auto_strip_and_convert_fields(model=model, data=row, make_instance=False) filter_dict = make_unique_filter_dict(model, data=data) split, created = model.objects.update_or_create(**filter_dict, defaults=data) if created: log.debug("Created a new split with the following parms:") log.debug(filter_dict) splits.append(split) return splits
def ajax_get_team_splits(request): log.debug("In get team splits") split_type = request.GET.get('split_type') filter_dict = { k: request.GET.get(k) for k in request.GET if k not in ['split_type', 'entity_id'] } filter_dict['team_id'] = request.GET.get('entity_id') log.debug(filter_dict) model = get_model(prefix="Team", middle=split_type, suffix="Split") splits = model.objects.filter(**filter_dict).order_by('season_id') model_fields_dict = get_user_exposed_model_fields( model, translation_style="upper", exclude=[k for k in filter_dict] + ['measure_type', 'season_id', 'team']) serialize_fields = [d['field_name'] for d in model_fields_dict] raw_data = simplejson.loads( serializers.serialize('json', splits, fields=serialize_fields)) splits_json = [entry['fields'] for entry in raw_data] data = {'model_fields': model_fields_dict, 'splits': splits_json} return JsonResponse(data)
def __init__(self, position, lup_date, scoring_settings, entry=None): # TODO: Right now scoring fields will come out in random order. # Maybe we can assign an ordering at creation of scoring settings? self.position = position self.display_position = POSITION_ORDER.get(position)[1] self.matchup = "" self.matchup_status = "" if entry is None: self.player = "None" self.player_id = 0 self.team = "N/A" self.eligibility_classes = " ".join( ["elig-" + str(x) for x in POSITION_ORDER.get(position)[2]]) for fld in scoring_settings.scoring_fields_vals: setattr(self, fld, "") else: self.player = entry.player.display_first_last self.player_id = entry.player.id self.team = entry.player.team.abbreviation self.eligibility_classes = " ".join([ "elig-" + x for x in entry.player.numbered_positions.split(",")[:-1] ]) base_box_score = PlayerTraditionalBoxScore.objects.filter( player=entry.player, game__game_date_est=lup_date) if base_box_score.exists(): self.matchup = base_box_score.first().matchup self.matchup_status = base_box_score.first( ).game.game_status_text split_fields_dict = defaultdict(list) for fld in scoring_settings.scoring_fields_vals: split_type, field = fld.split("__") split_fields_dict[split_type].append(field) for split_type in split_fields_dict: fields = split_fields_dict[split_type] if split_type in [ 'PlayerTracking', 'PlayerFourFactors', 'PlayerHustleStats' ]: suffix = "BoxScore" for fld in fields: setattr(self, split_type + "__" + fld, "TODO") continue else: suffix = "Split" model = get_model(middle=split_type, suffix=suffix) year = determine_season_for_date(lup_date) season = make_season_str(year) season_long_vals = model.objects.filter( season_id=year, player=entry.player, season_type="Regular Season", per_mode="PerGame", group_set="Overall", group_value=season).values(*fields) if season_long_vals.exists(): split = season_long_vals.first() for fld in fields: log.debug((split_type, fld, split[fld])) setattr(self, split_type + "__" + fld, split[fld])
def fetch_raw_data(self, season=None, season_type=REGULAR_SEASON, pt_measure_type=SPEED_DISTANCE, per_mode=TOTALS, group_set="Overall", group_value=None): self.raw_data = [] self.pt_measure_type = pt_measure_type if self.pt_measure_type in ["CatchShoot", "PullUpShot"]: middle = "ShotType" elif "Touch" in self.pt_measure_type or "Drive" in self.pt_measure_type: middle = "Touch" else: middle = self.pt_measure_type self.model = get_model(prefix="Player", middle=middle, suffix="Tracking") # Silly way to do this, I know url = self.base_url + self.endpoint if season is None: season = make_season_str(determine_season_for_date(date.today())) if group_set == "Overall" and group_value is None: group_value = season self.params['Season'] = str(season) self.params['SeasonType'] = season_type self.params['PerMode'] = per_mode self.params['PtMeasureType'] = pt_measure_type if group_set != "Overall": self.params[group_set] = group_value if group_set != "Month": group_value = GROUP_VALUES[group_value] log.debug(("Fetching Player Stats: ", season, season_type, pt_measure_type, per_mode, group_set, group_value)) raw_json = get_json_response(url, self.params) rset = raw_json['resultSets'][0] player_rows = dictify(result_set=rset) processed_rows = [] for row in player_rows: row['PLAYER'] = Player.objects.get(player_id=row['PLAYER_ID']) row['GROUP_SET'] = group_set row['SEASON'] = season row['SEASON_TYPE'] = season_type row['PT_MEASURE_TYPE'] = pt_measure_type row['PER_MODE'] = per_mode if group_set == "Month": row['GROUP_VALUE'] = REVERSE_MONTH_MAP[group_value] else: row['GROUP_VALUE'] = group_value if self.pt_measure_type in ["CatchShoot", "PullUpShot"]: row = convert_shot_type_dict_to_apex(row) elif "Touch" in self.pt_measure_type or "Drive" in self.pt_measure_type: row = convert_touch_dict_to_apex(row) proc_row = convert_dict_keys_to_lowercase( row, override_list=['GROUP_SET', 'GROUP_VALUE']) processed_rows.append(proc_row) self.raw_data = processed_rows