Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

412
Views
Django serializers, foreignkeys error

On the serializer im trying to show the person data into Employee but im getting this error AttributeError when attempting to get a value for field persons on serializer EmployeeSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Employee instance. Original exception text was: 'Employee' object has no attribute 'persons'.

Here's my models.py

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    curp = models.CharField(max_length=50)
    rfc = models.CharField(max_length=12)
    gender = models.CharField(max_length=20)



class Employee(models.Model):
    id = models.IntegerField(primary_key=True)
    joining_date = models.DateField()
    salary = models.DecimalField(18, decimal_places=2, max_digits=50)
    status = models.IntegerField()
    person = models.ForeignKey(Person, related_name='persons', on_delete=models.CASCADE)
    user = models.ForeignKey(User)
    branch = models.ForeignKey(Branch)

Serializers

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('name', 'curp', 'rfc', 'gender')

class EmployeeSerializer(serializers.ModelSerializer):
    persons = PersonSerializer(many=True)


    class Meta:
       model = Employee
       fields = ('persons')

It's my first time working on django so i dont get how to call the foreing keys. In my database i have the table Employee with 3 foreign keys (user, person and branch) Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In your Employee serializer you should changed name persons variable to person, and i assume since only one person would be related with employee object you can change the many to False

class EmployeeSerializer(serializers.ModelSerializer):
    person = PersonSerializer(many=False, )


    class Meta:
       model = Employee
       fields = ('person')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!