0

I'm 2 weeks into django so this might be dumb! In my django project, I have 3 models, Teacher, Student and a CustomUser. CustomUser has 2 fields first_name and last_name. Student has 3 fields grade, field_of_study and user which is a foreign key to CustomUser. Now inside my StudentSerializer I want to serialize first_name, last_name, grade and field of study. But because the last 2 field are not direct fields of Student, I cannot do that. Anyone know how this should be handled?

I also came across this Retrieving a Foreign Key value with django-rest-framework serializers but the answer didn't help really.

Arian Hassani
  • 89
  • 1
  • 8

1 Answers1

0

I did it like this and it worked like a charm. Hope the answer helps a newbie in the future!

class StudentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField()
firstname = serializers.CharField(source='user.firstname')
lastname = serializers.CharField(source='user.lastname')

class Meta:
    model = Student
    fields = ('firstname', 'lastname', 'id', 'school', 'field_of_study')
Arian Hassani
  • 89
  • 1
  • 8