Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9204315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:41:03+00:00 2026-06-17T23:41:03+00:00

I’m creating a website about baseball player for learning purpose. I’m stock in how

  • 0

I’m creating a website about baseball player for learning purpose. I’m stock in how to handle the foreign keys.
Here is my model:

class Player_Bios(models.Model):

   mlb_id           = models.SlugField(unique=True)    
   name             = models.CharField(max_length=50) 
   last             = models.CharField(max_length=50)
   middle           = models.CharField(max_length=50, blank=True)
   jersey           = models.CharField(max_length=5)
   def __unicode__(self):
        return self.mlb_id


class Stat (models.Model):
   player_id       = models.ForeignKey('Player_Bios')
   year            = models.IntegerField(max_length=50)
   h               = models.IntegerField(max_length=50)
   2h              = models.IntegerField(max_length=50)



   def __unicode__(self):
       return self.stat_id

So I’m able to go get the players stat, but how do I save them to database?

Example of what I want to do. I was able to collect and save all of the players that I want to have on my website and saved all of their bios. The only thing that I need is the players Career Stat.

from player_bios.models import *

year = "2012"     # I use variable in this example because I don't want to put all my code
h    = 180        #But think that I have this info
2h   = 30
st= Stat(player_id=, year=year,h=h,2h=2h)  #I don't know what to use on player id because                     that's the foreign key
st. save            

UPDATE:

I’m still having issues saving the data to the database.
Here is my code:

from django.core.management.base import BaseCommand, CommandError
from player_bios.models import *
import urllib2
import json
import string
import re


DR_ID = [u'430947', u'499864', u'405395']
stint = ["player_id","sport_code","ab","league_full","bb","ops","hr","season","ao","team_id",
    "go","cs","league_short","avg","go_ao","sport_id","team_full","league","sport","gidp",
    "d","g","team_abbrev","league_id","h","ibb","team_seq","sf","sac","team_short","r","so",
    "t","rbi","sb","slg","tb","hbp","obp"]
st = {}

class Command(BaseCommand):

for i in DR_ID:
    url = ("http://mlb.mlb.com/lookup/json/named.sport_hitting_composed.bam?game_type='R'&sport_code='mlb'&sport_code='aaa'&sport_code='aax'&sport_code='afa'&sport_code='afx'&sport_code='asx'&sport_code='rok'&sort_by='season_asc'&player_id="+i+"&sport_hitting_composed.season=2013")
    res = urllib2.urlopen(url)
    data = json.load(res)
    numberofseasons = data['sport_hitting_composed']['sport_hitting_tm']['queryResults']['totalSize']
    numberofseasons= int(numberofseasons)
    row = 0

    while row < numberofseasons:

        for x in stint:

            data2 = data['sport_hitting_composed']['sport_hitting_tm']['queryResults']['row'][row][x]
            st[x]=data2


        row +=1
        p_id = p=Player_Bios.objects.get(mlb_id=i)
        p_id_st=str(p_id)
        bat_id = (st['season']+st["team_id"])
        bat_id = p_id_st + bat_id
        c = BatStat(player_id_id= p_id.mlb_id,bat_stat_id=bat_id, sport_code = st["sport_code"],ab=st['ab'],league_full=st['league_full'],bb=st['bb'],ops=st['ops'],hr=st['hr'],season=st['season'],ao=st['ao'],
                    team_id=st['team_id'],go=st['go'],cs=st['cs'],league_short=st['league_short'],avg=st['avg'],go_ao=st['go_ao'],sport_id=st['sport_id'],team_full=st['team_full'],
                    league=st['league'],sport=st['sport'],gidp=st['gidp'],d=st['d'],g=st['g'],team_abbrev=st['team_abbrev'],league_id=st['team_id'],h=st['h'],ibb=st['ibb'],
                    team_seq=st['team_seq'],sf=st['sf'],sac=st['sac'],team_short=st['team_short'],r=st['r'],so=st['so'],t=st['t'],rbi=st['rbi'],sb=st['sb'],slg=st['slg'],tb=st['tb'],
                    hbp=st['hbp'],obp=st['obp'])
        c.save()   

I get the following error:

django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key      constraint fails (`player_bios_info`.`player_bios_batstat`, CONSTRAINT `player_id_id_refs_id_ee2da61` FOREIGN KEY (`player_id_id`) REFERENCES `player_bios_player_bios` (`id`))')

In the model I have the player_id, but on the database I see it as player_id_id.
Thanks in advance

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:41:04+00:00Added an answer on June 17, 2026 at 11:41 pm

    You need to create form so that it’s easy for you to select player. If you want to add just like what you did manually, it will be difficult for you.

    forms.py

    class StatForm(forms.ModelForm):
        class Meta:
            model = Stat
    
        def __init__(self, user, *args, **kwargs):
            super(StatForm, self).__init__(*args, **kwargs)
            self.fields['player_id'].queryset = Player_Bios.objects.filter()
    

    views.py

    def add_stat(request):
        if request.method == 'POST':
            form = StatForm(request.POST)
            if form.is_valid():
                form.save() 
    return render(request, 'add_stat.html', {
        'form': StatForm(),
    }) 
    

    add_stat.html

    <form method="post">{% csrf_token %}
        {% for field in form %}
            {{field}}<br/>
        {% endfor %}
        <input type="submit" value="Save Stat">
    </form>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I don't have much knowledge about the IPv6 protocol, so sorry if the question
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am using Paperclip to handle profile photo uploads in my app. They upload
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.