0

I want to use nested serializer for order with order contents but getting attribute error

as per Additional Serializer Fields in Django REST Framework 3 it is because the ordercontent field is not in order model

I searched for adding a non-model field to the serializer Add a non-model field on a ModelSerializer in DRF 3 but still getting the error

one interesting thing is that it's giving no errors in python manage.py shell

serializers.py


class OrderContentSerializer(ModelSerializer):
    class Meta:
        model = OrderContent
        fields = ('price',)




class OrderSerializer(ModelSerializer):
    order_contents = OrderContentSerializer(many=True)
    class Meta:
        model = Order
        fields = ('total_price', 'order_status', 'order_contents')
    def create(self, validated_data):
        contents_data = validated_data.pop('order_contents')
        order = Order.objects.create(**validated_data)        
        for data in contents_data:
            OrderContent.objects.create(order=order, **data)
        return order

views.py

class CreateOrderCustomer(APIView):
    # permission_classes = (IsAuthenticated,)
    def post(self, request):
        print(request.data)
        serializer = serializers.OrderSerializer(data=request.data)
        print(request.data)
        if serializer.is_valid():
            print(request.data)
            print(request.user)
            serializer.save(created_by=request.user)
            return Response(data=serializer.data,status= status.HTTP_201_CREATED)
        return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST)

i used python manage.py shell which successfully created the order

>>> from orders.serializers import OrderSerializer
>>> data={'totalprice': 3.0, 'order_status': 0, 'order_contents': [{'price': 18}, {'price': 12}]}
>>> serializer=OrderSerializer(data=data)
>>> serializer.is_valid()
True
>>> from users.models import User
>>> user=User.objects.get(username='1')
>>> serializer.save(created_by=user)
<Order: order7>

but doing same through views endpoint with the same data gives me

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

2
  • i was able to make it work by adding required=False in orderserializer as order_contents = OrderContentSerializer(many=True,required=False) Commented Jun 20, 2019 at 6:06
  • see stackoverflow.com/questions/28532420/… Commented Sep 18, 2019 at 2:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.