在Django DRF中将ArrayModelField序列化为JSON

时间:2019-12-19 13:15:41

标签: django django-rest-framework djongo

我正在Django 2.2中使用Djongo。我正在使用MongoDb和Djongo。我在GET API中遇到问题。 Comment模型未序列化。以下是代码段。

models.py

import uuid
from djongo import models

class Comment(models.Model):
    text = models.TextField();
    author = models.TextField();

    class Meta:
        abstract = True

    def __str__(self):
        return self.author +self.text

class Scene(models.Model):
    id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False)
    title = models.CharField(max_length=100)
    comments = models.ArrayModelField(
        model_container = Comment,
    );

    def __str__(self):
        return self.title

serializers.py

from rest_framework import serializers
from planning.models import Scene, Comment
class CommentSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Comment
        fields = ('text', 'author')

class SceneSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Scene
        comments = CommentSerializer();
        fields = ('id', 'title', 'comments')

viewsets.py

from planning.models import Scene, Comment
from .serializers import  SceneSerializer, CommentSerializer
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics
from rest_framework.generics import RetrieveUpdateDestroyAPIView

class SceneViewSet(viewsets.ModelViewSet):
    queryset = Scene.objects.all()
    serializer_class = SceneSerializer

class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

DRF中GET场景模型的输出

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": "28db3aa8-34ef-4880-a3eb-57643814af22",
        "title": "scene 1",
        "comments": "[<Comment: edwardcomment1>, <Comment: edwardcomment2>]"
    }
]

预期产量

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": "28db3aa8-34ef-4880-a3eb-57643814af22",
        "title": "scene 1",
        "comments": "[  { name : edward, text: comment1 }, 
            { name : edward, text: comment2 } ]"
    }
]

Djongo的ArrayModelField注释未按预期正确序列化。

1 个答案:

答案 0 :(得分:2)

在Meta之外序列化comments

from rest_framework import serializers
from planning.models import Scene, Comment

class CommentSerializer(serializers.ModelSerializer):

   class Meta:
      model = Comment
      fields = ('text', 'author')


class SceneSerializer(serializers.ModelSerializer):
   comments = CommentSerializer(many=True, read_only=True)

   class Meta:
      model = Scene
      fields = ('id', 'title', 'comments')

DRF nested relationships