2017-06-13 63 views
-1

我對Python和Django都很陌生,我很感謝我對Django REST,嵌套JSON和序列化程序的問題提供了一些指導。Django 1.11.2序列化程序嵌套的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) 

該錯誤

Got AttributeError when attempting to get a value for field Server on serializer ServersSerializer . The serializer field might be named incorrectly and not match any attribute or key on the Servers instance. Original exception text was: 'Servers' object has no attribute 'Server'.

+0

我更新了帖子,使其更有意義。 這是數據如何到達我的django rest api。 – user2519486

+0

你能展示視圖嗎? – zaidfazil

回答

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() 
+0

謝謝你的協助。 POST請求不會引發異常,但它也不會將數據放入表中。 – user2519486

+0

嘗試覆蓋串行器中的創建方法 – zaidfazil

+0

您是否嘗試在調用serializer.is_valid()後嘗試打印serializer.data() – zaidfazil