Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework: Insert multiple objects in one post request

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.

like image 338
Nenad Živanović Avatar asked Jan 04 '23 15:01

Nenad Živanović


1 Answers

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', 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
        )
like image 51
Brown Bear Avatar answered Jan 13 '23 10:01

Brown Bear