在视图中使用嵌套的可写序列化程序会导致AttributeError:

时间:2019-06-20 05:52:21

标签: django-rest-framework django-serializer

我想对订单内容使用订单的嵌套序列化器,但出现属性错误

根据Additional Serializer Fields in Django REST Framework 3,这是因为ordercontent字段不在订单模型中

我搜索了向序列化器添加非模型字段 Add a non-model field on a ModelSerializer in DRF 3 但仍然出现错误

一件有趣的事情是,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)

我使用了成功创建订单的python manage.py shell

>>> 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>

但通过具有相同数据的View端点进行相同操作会给我

AttributeError:尝试在序列化程序order_contents上获取字段OrderSerializer的值时,出现AttributeError。 序列化程序字段的名称可能不正确,并且与Order实例上的任何属性或键都不匹配。 原始异常文本为:“订单”对象没有属性“订单内容”。

0 个答案:

没有答案