0

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

模型.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

序列化程序.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')

视图集.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 的 Comment 未按预期正确序列化。

4

1 回答 1

2

comments在 Meta 之外序列化:

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 嵌套关系

于 2019-12-19T13:47:18.467 回答