Viktor Danilov Viktor Danilov - 2 months ago 29x
JSON Question

REST Framework: how to serialize objects?

I want to create a ListView with a array of nested objects. Here what I've tried so far:

class GroupDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = (

class GroupDetailView(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = GroupDetailSerializer

def get_queryset(self):
return Group.objects.all()

class Group(models.Model):
office = models.ForeignKey(Offices)
num = models.IntegerField()

def students(self):
from pupils.models import Pupils
return Pupils.objects.filter(group=self)

But it returns a type error:

<Pupils: John Doe> is not JSON serializable

I guess I need to use another serializer on my
field, but how?


Error is because your model is not json serializable.

you can see @yuwang comment to follow nested serializer

or for now, particular for this case you can change your code to:

def students(self):
    from pupils.models import Pupils
    return list(Pupils.objects.filter(group=self).values())