使用Django DRF在ArrayModelField中进行POST和PATCH操作

时间:2019-12-20 15:06:35

标签: django django-rest-framework djongo

我正在将Django 2.2和MongoDb与Djongo一起使用。我在POST和PATCH API中遇到问题。我面临三种问题。

  1. 执行POST操作以创建新条目时,API失败,并显示错误:数组项必须是模型实例
  2. 在POST API中引用Screenplay类的实例的正确方法是什么。父类的ID是否足够?
  3. 如何对场景模型中的特定字段(包括注释中的文本字段)执行更新?

以下是代码段。

示例POST API数据

{
    "title": "intro1",
    "screenplay": "49423c83-0078-4de1-901c-f9176b51fd33",
    "comments": [
        {
            "text": "hello world",
            "author": "director"
        }
    ]
}

models.py

import uuid
from djongo import models

class Screenplay(models.Model):
    id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False)
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title

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

    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)
    screenplay = models.ForeignKey(Screenplay, related_name='scenes', on_delete=models.CASCADE)

    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 ScreenplaySerializer(serializers.ModelSerializer):

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

class CommentSerializer(serializers.HyperlinkedModelSerializer):

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

class SceneSerializer(serializers.HyperlinkedModelSerializer):
    comments = CommentSerializer();

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

viewsets.py

from planning.models import Screenplay, Scene, Comment
from .serializers import  ScreenplaySerializer, 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 ScreenplayViewSet(viewsets.ModelViewSet):
    queryset = Screenplay.objects.all()
    serializer_class = ScreenplaySerializer

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

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

1 个答案:

答案 0 :(得分:0)

我建议您阅读Writable nested representations上的文档,这将有助于消除您的疑问。