darkstar
darkstar

Reputation: 1008

Django Rest Framework Method returns Object of type User is not JSON serializable

So basically I have a django method that I pass into my serializer but it returns the error Object of type User is not JSON serializable Here are my files:

models.py:

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    friends = models.ManyToManyField(User, blank=True, related_name='friends')

    def friends_list(self):
        return self.friends.all()

    def number_of_friends(self):
        return self.friends.all().count()

serialzers.py:

from rest_framework import serializers
from .models import Profile


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = [
            'id',
            'first_name',
            'last_name',
            'user',
            'friends',
            'number_of_friends',
            'friends_list'
        ]

The issue comes with the "friends_list" method as the "number_of_friends" method works perfectly as intended. The entire model fields are working its just that one method that won't work. How can I resolve this?

Upvotes: 5

Views: 8827

Answers (1)

JPG
JPG

Reputation: 88689

This is because the friends_list(...) method returning a QuerySet object and DRF is unable to serializer the same.

For that, you need to use the serializers.SerializerMethodField along with a separate serializer class to serialize the User objects

from rest_framework import serializers
from .models import Profile


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "first_name", "email")


class ProfileSerializer(serializers.ModelSerializer):
    friends_list = serializers.SerializerMethodField()

    def get_friends_list(self, profile):
        return UserSerializer(profile.friends_list(), many=True).data

    class Meta:
        model = Profile
        fields = [
            'id',
            'first_name',
            'last_name',
            'user',
            'friends',
            'number_of_friends',
            'friends_list'
        ]

Upvotes: 13

Related Questions