Why django-rest-framework doesn't display OneToOneField data - django

448 Views Asked by At

I want to set up restful API in my site. I used django-rest-framework. When I get an object from database, it doesn't show related object.

Below snippet is my first model (parent model):

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    family = models.CharField(max_length=50)

and the below snippet is my second model (child model):

class Klass(models.Model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    teacher = models.ForeignKey(Profile,related_name='teacher', on_delete=models.CASCADE)
    university = models.CharField(max_length=50, blank=True, null=True)

as you see in the second snippet, the teacher gets its value from Profile model.

But in django-rest-framework API view, instead of displaying the teahcer's name, it displays the pk.

The below snippets is my serializer and view:

# serializer
class KlassSerializer(serializers.ModelSerializer):

    class Meta:
        model = Klass
        fields = ('id', 'title', 'description', 'teacher')

# view
class KlassView(APIView):

    def get(self, request, pk=None):
        if pk is not None:
            klass = Klass.objects.filter(pk=pk).get()
            serializer = KlassSerializer(klass)
            return Response({'message': 'class get ', 'data': serializer.data,})

and this is the result:

{
    "message": "class get ",
    "data": {
        "id": 13,
        "title": "ُThe First Class",
        "description": "Nothing for now!",
        "teacher": 2
    }
}

How can I solve the problem? thanks

1

There are 1 best solutions below

1
On BEST ANSWER

try it, more detaile nested-relationships

class TeacherSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ('name')

class KlassSerializer(serializers.ModelSerializer):
    teacher = TeacherSerializer(read_only=True)

    class Meta:
        model = Klass
        fields = ('id', 'title', 'description', 'teacher')