Nested serialization for one to many

46 views
Skip to first unread message

sachin agarwal

unread,
Sep 8, 2020, 10:56:49 AM9/8/20
to Django REST framework
Hi All,

I have created Nested serialization for one to many, it work fine on my windows machine while it dosnt work on my 2nd ubuntu machine. 
django 2.2
djangorestframework 3.11.1

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

Your help would be highly appreciated.! Thanks in advance

Below is code. 
admin.py
from django.contrib import admin

# Register your models here.
from .models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)

models.py
import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published', null=True)
    author = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.question_text
       
    #def was_published_recently(self):
        #now = timezone.now()
        #return now - datetime.timedelta(days=1) <= self.pub_date <= now
   

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

serialize.py
from rest_framework import serializers
from . models import Choice, Question

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('choice_text','votes')


class QuestionSerializer(serializers.ModelSerializer):
    choice_set2 = ChoiceSerializer(many=True)

    class Meta:
        model = Question
        fields = ('pub_date', 'question_text', 'choice_set2')
       # depth = 1

    def create(self, validated_data):
        choice_validated_data = validated_data.pop('choice_set2')
        question = Question.objects.create(**validated_data)
        print("Print question****")
        print(question)
        choice_set2_serializer = self.fields['choice_set2']
        for each in choice_validated_data:
            each['question'] = question
            print("printing child data***********")
            print(each)
        choices2 = choice_set2_serializer.create(choice_validated_data)
        return question

views.py
from django.shortcuts import render

# Create your views here.
#from django.http import HttpRespose
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse
from rest_framework import status
from rest_framework.decorators  import api_view
from django.views.decorators.csrf import csrf_exempt
from . models import Question, Choice
from . serializers import QuestionSerializer, ChoiceSerializer
from rest_framework import viewsets

class ClientAPIView3(viewsets.ViewSet):
   
    def list(self, request):
        client = Question.objects.all()
        print(client)
        serializer = QuestionSerializer(client, many=True)
        print(serializer)
        return Response(serializer.data)

    def create(self, request):
        #print(request.data)
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            print("in vew create() is_valid**************")
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        print("...may be not()?? "+str(serializer.errors))
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def retrive(self, request, pk):
        queryset = Client.objects.all()
        client = get_object_or_404(queryset, pk=pk)
        serializer = ClientSerializer(client)
        return Response(serializer.data)

urls.py
from django.urls import path, include
#from rest_framework.urlpatterns import format_suffix_patters
from .views import ClientAPIView3
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
#outer.register('ClientAPIView2',ClientAPIView2)
router.register('ClientAPIView3',ClientAPIView3, basename='ClientAPIView3')
#outer.register('DeliveryAddressAPIView2',DeliveryAddressAPIView2)

urlpatterns = [
    path('', include(router.urls)),
]

test data
{
"question_text":"BPM is?",
"pub_date":"2020-09-08T10:10",
    "author":"Sachin Agarwal",
   "choice_set":[{
            "choice_text": "Business Process Monitoring", "votes":10
        },
        {
            "choice_text": "Business Performance Measurement","votes":20
        }
        ]
}
Using SQLite db for this work.

Reply all
Reply to author
Forward
0 new messages