Django 1.11.2序列化器嵌套json数组

时间:2017-06-13 11:17:01

标签: django serializer

我是Python和Django的新手,我很欣赏一些关于Django REST,嵌套JSON和序列化器问题的指导。

我希望发布:

{ "Server": [
    {
    "serverSerialNumber": "0000",
    "serverUniqueKey": "2222"
    },
    {
    "serverSerialNumber": "0001",
    "serverUniqueKey": "2223"
    }
]
}

这是我的序列化器:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import Api

class ApiSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Api
        fields = ('id', 'serverSerialNumber', 'serverUniqueKey', 'date_created', 'date_modified')
        read_only_fields = ('date_created', 'date_modified')
        depth = 1

我只是收到以下内容:

{
    "serverSerialNumber": [
        "This field is required."
    ]
}

所以我不明白如何使用'深度'或者我正在做些傻事。

根据请求添加视图:

from django.shortcuts import render

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import generics
from .serializers import ApiSerializer
from .models import Api

class CreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = Api.objects.all()
    serializer_class = ApiSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new item."""
        serializer.save()

好的,所以我偶然发现了一些文档并对此进行了另一次打击。 仍然没有工作,但代码似乎更有意义,这里是新的代码和错误:

serializers.py

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import Blade, Servers

class BladeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blade
        fields = ('id', 'serverSerialNumber', 'serverUniqueKey', 'date_created', 'date_modified')
        read_only_fields = ('date_created', 'date_modified')

class ServersSerializer(serializers.ModelSerializer):
    Server = BladeSerializer(many=True)

    class Meta:
        model = Servers
        fields = ['Server']

    def create(self, validated_data):
        servers_data = validated_data.pop('Server')
        srv = Servers.objects.create(**validated_data)
        for server_data in servers_data:
            Blade.objects.create(srv=srv, **server_data)
        return srv

views.py

from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from api.serializers import UserSerializer, GroupSerializer
from rest_framework import generics
from .serializers import BladeSerializer, ServersSerializer
from .models import Blade, Servers

class CreateView(generics.ListCreateAPIView):
    queryset = Servers.objects.all()
    serializer_class = ServersSerializer

    def perform_create(self, serializer):
        serializer.save()

models.py

from django.db import models
from inventory.models import Server

class Blade(models.Model):
    instanceId = models.CharField(max_length=255, blank=True, unique=False)
    chassisUniqueKey = models.CharField(max_length=255, blank=True, unique=False)
    serverUniqueKey = models.CharField(max_length=255, blank=True, unique=False)
    serverSerialNumber = models.CharField(max_length=255, blank=False, unique=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __str__(self):
            return "{}".format(self.name)

class Servers(models.Model):

    Servers = models.CharField(max_length=10, blank=True, unique=False)

    def __str__(self):
            """Return a human readable representation of the model instance."""
            return "{}".format(self.name)

错误

  尝试在序列化程序Server上获取字段ServersSerializer的值时,

出现AttributeError。   序列化程序字段可能名称不正确,并且与Servers实例上的任何属性或键都不匹配。   原始异常文本是:'Servers'对象没有属性'Server'。

1 个答案:

答案 0 :(得分:0)

试试这个,

class CreateView(generics.ListCreateAPIView):
    queryset = Api.objects.all()
    serializer_class = ApiSerializer 

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data) 
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()