Instance Error On Foreign Key Field Django

Im stumped and need help on my function. I have two tables student and student information. Student information is all guardian information of that student. I separated this data from the main student table so you can add as many guardians as you want to a students file with new records. The error I’m getting is as followed.

Cannot assign "’1’": "StudentInformation.studentpsid" must be a "Student" instance.

Attached you will see my code. Studentpsid in student information is a foreign key from student.

def ImportStudentGuardian(request):     AuthTokenP(request)     print("Getting student guardian data from SIS for K-8")     #Pulls K-8 Guardians     url = "removed for posting"     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')     xml_string = ET.fromstring(encode_xml)     students = xml_string.findall("student")     for student in students:       #XML Values       psid = student.find("id").text       try:        mother = student.find("contact").find("mother").text       except Exception:        mother = ""          try:         father = student.find("contact").find("father").text       except Exception:        father = ""        if Student.objects.filter(studentpsid=psid).exists():           print("Accessing guardian information.")         m = StudentInformation.objects.create(studentpsid=psid,guardian_name = mother, relation = "Mom")   <---- Function Fails here         print("Record doesn't exist for mom, creating record.")         m.save()         d= StudentInformation.objects.create(studentpsid=psid,guardian_name = father, relation = "Dad")         print("Record doesn't exist for dad, creating record.")         d.save()       return ("Updated Guardian Information ") 
Model  class Student(models.Model):     studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)     student_name = models.CharField(max_length = 50)     first_name = models.CharField(max_length = 50, default = "")     last_name = models.CharField(max_length = 50,default = "")     gender = models.CharField(max_length = 1,default = "")     student_grade = models.CharField(max_length = 2, default = "")     home_room = models.CharField(max_length = 5, default = "")     student_enrollment = models.CharField(max_length = 2, default = "")     school_number = models.CharField(max_length = 15, default = "")      email = models.EmailField(default = "")     projected_graduation_year = models.CharField(max_length = 4, default = "")     counseling_goal = models.TextField(max_length = 255)     class_name = models.ManyToManyField(TeacherClass)     image = models.ImageField(default ="default.png", upload_to ='student_pics')  # Guardian Information For Student  class StudentInformation(models.Model):       studentpsid = models.ForeignKey(Student,on_delete = models.CASCADE, default = "" ,)        guardian_name = models.CharField(max_length = 50, default = "")       RELATION_CHOICES = [         (0, 'None'),           (1, 'Mom'),         (2, 'Dad'),         (3, 'Other'),              ]       relation = models.PositiveSmallIntegerField(choices = RELATION_CHOICES,)       guardian_cell = models.CharField(max_length = 12, default = "")       guardian_email = models.EmailField(max_length = 80,blank = True, default = "")       prefered_contact = models.BooleanField(default = False, blank = True)       DAY_CHOICES = [         (0, 'None'),           (1, 'Monday'),         (2, 'Tuesday'),         (3, 'Wednesday'),         (4, 'Thursday'),         (5, 'Friday'),              ]       day_of_week =  models.PositiveSmallIntegerField(choices = DAY_CHOICES, default = 0 )       time = models.CharField(max_length= 7, default = "", blank = True)        
Add Comment
2 Answer(s)

While creating a record with the foreign key relation, and instance of the related table should be provided, so the table can maintain a relationship for that particular record.

Get the instance of the Student table with the given psid and use that while creating the StudentInformation record

EDIT : Included the part for creating the record only if mother and father values are available.

for student in students:       #XML Values     psid = student.find("id").text     try:         psid_obj = Student.objects.get(studentpsid=psid) #(pk = psid) also works as the field is primary key         try:             mother = student.find("contact").find("mother").text             m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = "Mom")             m.save()         except Exception as err1:             print "Error at Mom", str(err1)            try:              father = student.find("contact").find("father").text             d= StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = father, relation = "Dad")             d.save()         except Exception as err2:             print "Error at Dad",str(err2)     except:         print "Student Record Not found" 
Answered on July 16, 2020.
Add Comment

As the error says, you are assigning a char data type to the ForeignKey field.

You should first get the instance of that Student, and then assign it to your StudentInformation object, like this:

if Student.objects.filter(studentpsid=psid).exists():           print("Accessing guardian information.")         student = Student.objects.get(pk=psid)  # this will fail if the student doesn't exist         m = StudentInformation.objects.create(studentpsid=student,guardian_name = mother, relation = "Mom")   <---- Function Fails here         print("Record doesn't exist for mom, creating record.")         m.save()         d= StudentInformation.objects.create(studentpsid=student,guardian_name = father, relation = "Dad")         print("Record doesn't exist for dad, creating record.")         d.save()       return ("Updated Guardian Information ") 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.