Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

414
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda