简体   繁体   中英

FOREIGN KEY constraint failed Django 3.1.1

I have a API script that uploads my term dates. For Some reason I keep getting an error that I have a FOREIGN KEY constraint failed when the script runs. Appreciate any help on how to fix this. Attached is my models and my script. None of the data will save to the table. I appreciate any help you guys can give me. Thank you so much!

models.py

# School Information Stored
class School(models.Model):
    school_name = models.CharField(max_length = 50, default = "")
    schoolpsid_id= models.CharField(default = "", max_length = 50, unique = True)
    school_number = models.CharField(primary_key = True,default = "", max_length = 50, unique = True)
    low_grade = models.CharField(default = "", max_length = 2 )
    high_grade = models.CharField(default = "", max_length = 2 )
    

    class Meta:
       verbose_name = "School"
    def __str__(self):
        return self.school_name


      # Term Information Stored
class Term(models.Model):
    termpsid= models.CharField(default = "", max_length = 10, unique = True)
    schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = "" ,) 
    start_year = models.CharField(max_length = 4, default = "")
    portion = models.CharField(max_length = 10, default = "")
    start_date = models.DateField(blank=True)
    end_date = models.DateField(blank= True)
    abbreviation = models.CharField(max_length = 50, default = "")
    name = models.CharField(max_length = 50, default = "")

    class Meta:
       verbose_name = "Term"
    def __str__(self):
        return self.name    


powerschool.py

def ImportTerms(request):
    print("Getting term data for K-8 (Creation-Update)")
    #Pulls The K-8 Term Data
    url = ""
    payload = {}
    token = APIInformation.objects.get(api_name="PowerSchool")
    key = token.key
    headers = {'Authorization': 'Bearer {}'.format(key)}   
    response = requests.request('GET', url, headers=headers, data = payload)
    encode_xml = response.text.encode('utf8')
    print("Analyzing term records for K-8")
    soup = BeautifulSoup(encode_xml, 'lxml')

    for term in soup.findAll('term'):
     #XML Values
     termpsid = term.find('id').text
     print('---->%s' %termpsid)
     # Updates Term Information If Exists 
     if Term.objects.filter(termpsid=termpsid).exists():
        try: 
          termpsid = term.find('id').text
          school_id = term.find('school_id').text
          start_year = term.find('start_year').text 
          portion = term.find('portion').text 
          start_date = term.find('start_date').text
          end_date = term.find('end_date').text 
          abbreviation = term.find('abbreviation').text 
          name = term.find('name').text 
          print('---->%s' %termpsid)
          print('---->%s' %school_id)
          print('---->%s' %start_year)
          print('---->%s' %portion)
          print('---->%s' %start_date)
          print('---->%s' %end_date)
          print('---->%s' %abbreviation)
          print('---->%s' %name)
          Term.objects(termpsid=termpsid).update(schoolpsid_id = school_id, start_year = start_year, portion = portion, start_date = start_date, end_date = end_date, abbreviation= abbreviation,
          name = name)
        except Exception as err1:
          print ("Error at Term", str(err1))
     else:
       try: 
         termpsid = term.find('id').text
         school_id = term.find('school_id').text
         start_year = term.find('start_year').text 
         portion = term.find('portion').text 
         start_date = term.find('start_date').text
         end_date = term.find('end_date').text 
         abbreviation = term.find('abbreviation').text 
         name = term.find('name').text 
         print('---->%s' %termpsid)
         print('---->%s' %school_id)
         print('---->%s' %start_year)
         print('---->%s' %portion)
         print('---->%s' %start_date)
         print('---->%s' %end_date)
         print('---->%s' %abbreviation)
         print('---->%s' %name)
         t =  Term.objects.create(termpsid=termpsid,schoolpsid_id = school_id, start_year = start_year, portion = portion, start_date = start_date, end_date = end_date, abbreviation= abbreviation,
         name = name)
         t.save()
       except Exception as err2:
            print ("Error at Term", str(err2))

    print("Getting term data for NHS School (Creation-Update)")
    #Pulls The NHS Term Data
    url = ""
    payload = {}
    token = APIInformation.objects.get(api_name="PowerSchool")
    key = token.key
    headers = {'Authorization': 'Bearer {}'.format(key)}   
    response = requests.request('GET', url, headers=headers, data = payload)
    encode_xml = response.text.encode('utf8')
    print("Analyzing term records for The Newmark School")
    soup = BeautifulSoup(encode_xml, 'lxml') 
    for term in soup.findAll('term'):
      #XML Values
     termpsid = term.find('id').text
     print('---->%s' %termpsid)
     # Updates Term Information If Exists 
     if Term.objects.filter(termpsid=termpsid).exists():
        try: 
          termpsid = term.find('id').text
          school_id = term.find('school_id').text
          start_year = term.find('start_year').text 
          portion = term.find('portion').text 
          start_date = term.find('start_date').text
          end_date = term.find('end_date').text 
          abbreviation = term.find('abbreviation').text 
          name = term.find('name').text 
          print('---->%s' %termpsid)
          print('---->%s' %school_id)
          print('---->%s' %start_year)
          print('---->%s' %portion)
          print('---->%s' %start_date)
          print('---->%s' %end_date)
          print('---->%s' %abbreviation)
          print('---->%s' %name)
          Term.objects(termpsid=termpsid).update(schoolpsid_id = school_id, start_year = start_year, portion = portion, start_date = start_date, end_date = end_date, abbreviation= abbreviation,
          name = name)
        except Exception as err3:
          print ("Error at Term", str(err3))
     else:
       try: 
         termpsid = term.find('id').text
         school_id = term.find('school_id').text
         start_year = term.find('start_year').text 
         portion = term.find('portion').text 
         start_date = term.find('start_date').text
         end_date = term.find('end_date').text 
         abbreviation = term.find('abbreviation').text 
         name = term.find('name').text 
         print('---->%s' %termpsid)
         print('---->%s' %school_id)
         print('---->%s' %start_year)
         print('---->%s' %portion)
         print('---->%s' %start_date)
         print('---->%s' %end_date)
         print('---->%s' %abbreviation)
         print('---->%s' %name)
         t =  Term.objects.create(termpsid=termpsid,schoolpsid_id = school_id, start_year = start_year, portion = portion, start_date = start_date, end_date = end_date, abbreviation= abbreviation,
         name = name)
         t.save()
       except Exception as err4:
            print ("Error at Term", str(err4))           

I was able to fix this. I had to specify all my default primary keys in the tables. It didn't like me referencing other fields that weren't primary keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM