简体   繁体   English

REST框架:如何序列化对象?

[英]REST Framework: how to serialize objects?

I want to create a ListView with a array of nested objects. 我想用嵌套对象数组创建一个ListView。 Here what I've tried so far: 这是我到目前为止尝试过的:

rest.py 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 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? 我想我需要在students字段中使用另一个序列化器,但是如何?

Error is because your model is not json serializable. 错误是因为您的模型不可json序列化。

you can see @yuwang comment to follow nested serializer http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects 您可以看到@yuwang评论来关注嵌套序列化程序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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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