简体   繁体   中英

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:

rest.py

class GroupDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = (
            'id',
            'num',
            'students',
        )

@permission_classes((permissions.IsAdminUser,))
class GroupDetailView(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = GroupDetailSerializer

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

models.py

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

    @property
    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 students field, but how?

Error is because your model is not json serializable.

you can see @yuwang comment to follow nested serializer http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM