4

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.

Brown Bear
  • 19,655
  • 10
  • 58
  • 76

1 Answers1

10

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
        )
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • I rewrite `data = request.data.get("items") if 'items' in request.data else data = request.data` to ` if 'items' in request.data: data = request.data.get("items") else: data = request.data` because I get this error `SyntaxError: can't assign to conditional expression` With rewrited code still get error `AssertionError at /api/sale_user/ Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.` – Nenad Živanović Aug 10 '17 at 09:57
  • i'm sorry, i fixed both troubles you may try again – Brown Bear Aug 10 '17 at 09:59
  • Ok, I tried again, now I have new error `NameError at /api/sale_user/ name 'status' is not defined` :( – Nenad Živanović Aug 10 '17 at 10:04
  • it is good :) just add `from rest_framework import status` to your imports – Brown Bear Aug 10 '17 at 10:07
  • glad to help you) – Brown Bear Aug 10 '17 at 10:15
  • getting error - name 'Response' is not defined. Although data is stored. Any advice on that? – bannedFromAskingQuestions Apr 08 '20 at 23:52
  • Got rid of it using 'from rest_framework.response import Response'. – bannedFromAskingQuestions Apr 08 '20 at 23:56
  • 1
    @yaksh added the import to the answer, for other who will search the same – Brown Bear Apr 09 '20 at 05:56
  • Hi @BearBrown, I would really appreciate if you can suggest any good place where I can learn Django Rest Framework in-depth. I have tried DRF documentation but it is a little tough for me. – bannedFromAskingQuestions May 25 '20 at 06:57
  • Hi, for me the good books is:[Two-Scoops-Django](https://www.amazon.com/Two-Scoops-Django-1-11-Practices/dp/0692915729/ref=pd_sbs_14_1/137-3095740-2195057?_encoding=UTF8&pd_rd_i=0692915729&pd_rd_r=bafad847-9834-45b0-bf8f-f93ac9031871&pd_rd_w=IZFXK&pd_rd_wg=SXsLn&pf_rd_p=12b8d3e2-e203-4b23-a8bc-68a7d2806477&pf_rd_r=9KQPWWMQM7P45Z7FWC58&psc=1&refRID=9KQPWWMQM7P45Z7FWC58) – Brown Bear May 25 '20 at 07:03