簡體   English   中英

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

[英]REST Framework: how to serialize objects?

我想用嵌套對象數組創建一個ListView。 這是我到目前為止嘗試過的:

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)

但它返回類型錯誤:

<Pupils: John Doe> is not JSON serializable

我想我需要在students字段中使用另一個序列化器,但是如何?

錯誤是因為您的模型不可json序列化。

您可以看到@yuwang評論來關注嵌套序列化程序http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

或現在,特別是在這種情況下,您可以將代碼更改為:

@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