Django rest framework: Insert multiple objects in one post request

∥☆過路亽.° 提交于 2020-01-01 07:19:12

问题


I am using DRF for my API backend. I need to insert multiple objects into one post request. I saw so many tutorials, as well How do I create multiple model instances with Django Rest Framework?, but not success. I am using ModelSerializer, but when using many=True then have problem with ListSerializer.

views.py

class SaleUserViewSet(ModelViewSet):
    queryset = SaleUser.objects.all()
    serializer_class = SaleUserSerializer(many=True)

serlializers.py

class SaleUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = SaleUser
        fields = ('id', 'comment', 'creation_date', 'modification_date', 'last_user', 'user', 'sale', 'user_sale_type')

error message

AttributeError at /api/sale_user/ type object 'Meta' has no attribute 'model'

Please advise.


回答1:


rollback serializer to your default

class SaleUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = SaleUser
        fields = ('id', 'comment', 'creation_date', 'modification_date', 'last_user', 'user', 'sale', 'user_sale_type')

and override view to it:

class SaleUserViewSet(ModelViewSet):
    queryset = SaleUser.objects.all()
    serializer_class = SaleUserSerializer

    def create(self, request, *args, **kwargs):
        data = request.data.get("items") if 'items' in request.data else request.data
        many = isinstance(data, list)
        print (data, many)
        serializer = self.get_serializer(data=data, many=many)
        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)


来源:https://stackoverflow.com/questions/45607644/django-rest-framework-insert-multiple-objects-in-one-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!