Django rest framework: Insert multiple objects in

2020-06-06 05:15发布

问题:

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:

from rest_framework.response import Response    

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)