djangodjango-modelsdjango-views

Django 2 DB columns as FK to the same related table


I have a table 'Athletes' and another table 'Parents'.

Table fields are: ATHLETES

  reg_number
  first_name
  last_name
  gender 
  age_group (as FK to AgeGroup)
  parent_1 (as FK to Parents using related_name='parent_1')
  parent_2 (as FK to Parents using related_name='parent_2')

PARENTS

  first_name
  last_name
  email
  phone

I have this working in the admin console where I can add parents to athletes.

I have a form that will display the related parents for each athlete.

Issue is trying to update the parent for a given athlete. POST has correct IDs for parent_1 and parent_2 but I get the following error within browser

ValueError at /save_athlete
Cannot assign "'1'": "Athletes.parent_1" must be a "Parents" instance.

POST has the following data showing in the payload

  id: 1
  reg_number: 12345
  group: 2
  first_name: amy
  last_name: small
  gender: Female
  parent_1: 1
  parent_2: 2

I don't understand the error so not sure what code would be useful to post here.

I had expected that the parent_1 and parent_2 values (ids) would be accepted when the form validates but it throws an error in views.py


Solution

  • I have solved my problem. When I added the 2 Parent_ FKs to the model I did not update the forms.py to have additional code that Group FK was using.

    def_clean_group code was existing.... I copied the example for parent_1 and the error moved to parent_2. created entry for parent_2 and problem resolved.

    def clean_group(self):
        group = self.data['group'] if (self.data['group']).isnumeric() else 0
        try:
            group = models.Groups.objects.get(pk = group)
            return group
        except:
            raise forms.ValidationError("Invalid Selected.")
    
    def clean_parent_1(self):
        parent_1 = self.data['parent_1'] if (self.data['parent_1']).isnumeric() else 0
        try:
            parent_1 = models.Parents.objects.get(pk = parent_1)
            return parent_1
        except:
            raise forms.ValidationError("Invalid Selected.")
    
    def clean_parent_2(self):
        parent_2 = self.data['parent_2'] if (self.data['parent_2']).isnumeric() else 0
        try:
            parent_2 = models.Parents.objects.get(pk = parent_2)
            return parent_2
        except:
            raise forms.ValidationError("Invalid Selected.")