How better way to create a function to pass a JSON by serializer in django rest?How to debug in Django, the good way?Creating a JSON response using Django and PythonDjango REST framework: non-model serializerHow can I do a bulk_create in django REST Framework with nested models?How can i correctly pass arguments to classbasedviews testing Django Rest Framework?Python Django rest-framework serializer omitting fieldHow to serialize GenericForeignKey in DRF?Django-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerDjango rest framework add more data when serialize many objectserializer.is_valid() works with integer fields but serializer.save() asks for model instance

Knights and Knaves: What does C say?

Mac disaster! No longer boots - can’t finish my uni stuff

Ĉi tie or ĉi-tie? Why do people sometimes hyphenate ĉi tie?

Why did they use ultrafast diodes in a 50 or 60 Hz bridge?

How important is knowledge of trig identities for use in Calculus

PhD Length: are shorter PhD degrees (from different countries) valued differently in other counter countries where PhD Is a longer process?

Can I bring this power bank on board the aircraft?

Why the first octet of a MAC address always end with a binary 0?

Notation clarity question for a conglomerate of accidentals

How to refresh wired service getRecord manually?

Why is there such a singular place for bird watching?

Why is music is taught by reading sheet music?

Digital Bananas

What did the Federation give the Prophets in exchange for access to the wormhole in DS9?

Rank-one positive decomposition for a entry-wise positive positive definite matrix

Can a passenger predict that an airline or a tour operator is about to go bankrupt?

Found a minor bug, affecting 1% of users. What should QA do?

How to level a picture frame hung on a single nail?

Isn't the detector always measuring, and thus always collapsing the state?

Job interview by video at home and privacy concerns

Is there a way to make an animal companion able to read a language?

Why Vegetable Stock is bitter, but Chicken Stock not?

IEEE 754 square root with Newton-Raphson

Is there a pattern for handling conflicting function parameters?



How better way to create a function to pass a JSON by serializer in django rest?


How to debug in Django, the good way?Creating a JSON response using Django and PythonDjango REST framework: non-model serializerHow can I do a bulk_create in django REST Framework with nested models?How can i correctly pass arguments to classbasedviews testing Django Rest Framework?Python Django rest-framework serializer omitting fieldHow to serialize GenericForeignKey in DRF?Django-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerDjango rest framework add more data when serialize many objectserializer.is_valid() works with integer fields but serializer.save() asks for model instance






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









1















I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.



For help I wrote a code example below.



Serialzer example:



class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage

class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car


Well. I need to update a car list through the garage serializer. I'm thinking anything like this:



(example view)



class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage

@action(detail=True, methods=['put'])
def update_car(self, request):
...
serializer = CarSerializer(queryset, many=True)
...
return Response(serializer.data)


Attempt 1:



Searching and reading the doc, I tried this way:



 @action(methods=['put'], detail=False)
def update_car(self, request, *args, **kwargs):
if request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CarSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)


But I received this error:



non_field_errors:
["Expected a list of items but got type "dict"."]


Attempt 2:



With a @fxgx I tried too:



 def update_car(self, request):
serializer = CarSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = dict(list(serializer.validated_data.items()))
queryset = Car.objects.update(**validated_data)
return Response(CarSerializer(queryset, many=True).data)


But I received this error:




"detail": "Not found."










share|improve this question
































    1















    I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.



    For help I wrote a code example below.



    Serialzer example:



    class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

    class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    model = Car


    Well. I need to update a car list through the garage serializer. I'm thinking anything like this:



    (example view)



    class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

    @action(detail=True, methods=['put'])
    def update_car(self, request):
    ...
    serializer = CarSerializer(queryset, many=True)
    ...
    return Response(serializer.data)


    Attempt 1:



    Searching and reading the doc, I tried this way:



     @action(methods=['put'], detail=False)
    def update_car(self, request, *args, **kwargs):
    if request.method == 'PUT':
    data = JSONParser().parse(request)
    serializer = CarSerializer(data=data, many=True)
    if serializer.is_valid():
    serializer.save()
    return JsonResponse(serializer.data)
    return JsonResponse(serializer.errors, status=400)


    But I received this error:



    non_field_errors:
    ["Expected a list of items but got type "dict"."]


    Attempt 2:



    With a @fxgx I tried too:



     def update_car(self, request):
    serializer = CarSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    validated_data = dict(list(serializer.validated_data.items()))
    queryset = Car.objects.update(**validated_data)
    return Response(CarSerializer(queryset, many=True).data)


    But I received this error:




    "detail": "Not found."










    share|improve this question




























      1












      1








      1








      I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.



      For help I wrote a code example below.



      Serialzer example:



      class GarageViewSet(viewsets.ModelViewSet):
      queryset = Garage.objects.all()
      serializer_class = GarageSerializer
      model = Garage

      class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
      queryset = Car.objects.all()
      serializer_class = CarSerializer
      model = Car


      Well. I need to update a car list through the garage serializer. I'm thinking anything like this:



      (example view)



      class GarageViewSet(viewsets.ModelViewSet):
      queryset = Garage.objects.all()
      serializer_class = GarageSerializer
      model = Garage

      @action(detail=True, methods=['put'])
      def update_car(self, request):
      ...
      serializer = CarSerializer(queryset, many=True)
      ...
      return Response(serializer.data)


      Attempt 1:



      Searching and reading the doc, I tried this way:



       @action(methods=['put'], detail=False)
      def update_car(self, request, *args, **kwargs):
      if request.method == 'PUT':
      data = JSONParser().parse(request)
      serializer = CarSerializer(data=data, many=True)
      if serializer.is_valid():
      serializer.save()
      return JsonResponse(serializer.data)
      return JsonResponse(serializer.errors, status=400)


      But I received this error:



      non_field_errors:
      ["Expected a list of items but got type "dict"."]


      Attempt 2:



      With a @fxgx I tried too:



       def update_car(self, request):
      serializer = CarSerializer(data=request.data)
      serializer.is_valid(raise_exception=True)
      validated_data = dict(list(serializer.validated_data.items()))
      queryset = Car.objects.update(**validated_data)
      return Response(CarSerializer(queryset, many=True).data)


      But I received this error:




      "detail": "Not found."










      share|improve this question
















      I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.



      For help I wrote a code example below.



      Serialzer example:



      class GarageViewSet(viewsets.ModelViewSet):
      queryset = Garage.objects.all()
      serializer_class = GarageSerializer
      model = Garage

      class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
      queryset = Car.objects.all()
      serializer_class = CarSerializer
      model = Car


      Well. I need to update a car list through the garage serializer. I'm thinking anything like this:



      (example view)



      class GarageViewSet(viewsets.ModelViewSet):
      queryset = Garage.objects.all()
      serializer_class = GarageSerializer
      model = Garage

      @action(detail=True, methods=['put'])
      def update_car(self, request):
      ...
      serializer = CarSerializer(queryset, many=True)
      ...
      return Response(serializer.data)


      Attempt 1:



      Searching and reading the doc, I tried this way:



       @action(methods=['put'], detail=False)
      def update_car(self, request, *args, **kwargs):
      if request.method == 'PUT':
      data = JSONParser().parse(request)
      serializer = CarSerializer(data=data, many=True)
      if serializer.is_valid():
      serializer.save()
      return JsonResponse(serializer.data)
      return JsonResponse(serializer.errors, status=400)


      But I received this error:



      non_field_errors:
      ["Expected a list of items but got type "dict"."]


      Attempt 2:



      With a @fxgx I tried too:



       def update_car(self, request):
      serializer = CarSerializer(data=request.data)
      serializer.is_valid(raise_exception=True)
      validated_data = dict(list(serializer.validated_data.items()))
      queryset = Car.objects.update(**validated_data)
      return Response(CarSerializer(queryset, many=True).data)


      But I received this error:




      "detail": "Not found."







      python django django-rest-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 2 at 20:54







      Joey Fran

















      asked Mar 28 at 21:15









      Joey FranJoey Fran

      788 bronze badges




      788 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1
















          DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:



           class GarageViewSet(viewsets.ModelViewSet):
          queryset = Garage.objects.all()
          serializer_class = GarageSerializer
          model = Garage

          @action(detail=False, methods=['put'])
          def update_car(self, request):
          ...
          # Use partial=True for partial updates.
          serializer = CarSerializer(data=request.data)

          # Validate data.
          serializer.is_valid(raise_exception=True)

          # Get validated data in dictionary format.
          validated_data = dict(list(serializer.validated_data.items()))

          # Update objects
          quertset.update(**validated_data)

          ...
          return Response(CarSerializer(queryset, many=True).data)





          share|improve this answer



























          • Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

            – Joey Fran
            Apr 2 at 20:39











          • I has some doubts about your example... I update my question.

            – Joey Fran
            Apr 2 at 20:55











          • @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

            – zeynel
            Apr 2 at 21:04











          • My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

            – Joey Fran
            Apr 2 at 21:44











          • Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

            – zeynel
            Apr 2 at 22:25













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );














          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406952%2fhow-better-way-to-create-a-function-to-pass-a-json-by-serializer-in-django-rest%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1
















          DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:



           class GarageViewSet(viewsets.ModelViewSet):
          queryset = Garage.objects.all()
          serializer_class = GarageSerializer
          model = Garage

          @action(detail=False, methods=['put'])
          def update_car(self, request):
          ...
          # Use partial=True for partial updates.
          serializer = CarSerializer(data=request.data)

          # Validate data.
          serializer.is_valid(raise_exception=True)

          # Get validated data in dictionary format.
          validated_data = dict(list(serializer.validated_data.items()))

          # Update objects
          quertset.update(**validated_data)

          ...
          return Response(CarSerializer(queryset, many=True).data)





          share|improve this answer



























          • Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

            – Joey Fran
            Apr 2 at 20:39











          • I has some doubts about your example... I update my question.

            – Joey Fran
            Apr 2 at 20:55











          • @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

            – zeynel
            Apr 2 at 21:04











          • My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

            – Joey Fran
            Apr 2 at 21:44











          • Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

            – zeynel
            Apr 2 at 22:25
















          1
















          DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:



           class GarageViewSet(viewsets.ModelViewSet):
          queryset = Garage.objects.all()
          serializer_class = GarageSerializer
          model = Garage

          @action(detail=False, methods=['put'])
          def update_car(self, request):
          ...
          # Use partial=True for partial updates.
          serializer = CarSerializer(data=request.data)

          # Validate data.
          serializer.is_valid(raise_exception=True)

          # Get validated data in dictionary format.
          validated_data = dict(list(serializer.validated_data.items()))

          # Update objects
          quertset.update(**validated_data)

          ...
          return Response(CarSerializer(queryset, many=True).data)





          share|improve this answer



























          • Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

            – Joey Fran
            Apr 2 at 20:39











          • I has some doubts about your example... I update my question.

            – Joey Fran
            Apr 2 at 20:55











          • @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

            – zeynel
            Apr 2 at 21:04











          • My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

            – Joey Fran
            Apr 2 at 21:44











          • Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

            – zeynel
            Apr 2 at 22:25














          1














          1










          1









          DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:



           class GarageViewSet(viewsets.ModelViewSet):
          queryset = Garage.objects.all()
          serializer_class = GarageSerializer
          model = Garage

          @action(detail=False, methods=['put'])
          def update_car(self, request):
          ...
          # Use partial=True for partial updates.
          serializer = CarSerializer(data=request.data)

          # Validate data.
          serializer.is_valid(raise_exception=True)

          # Get validated data in dictionary format.
          validated_data = dict(list(serializer.validated_data.items()))

          # Update objects
          quertset.update(**validated_data)

          ...
          return Response(CarSerializer(queryset, many=True).data)





          share|improve this answer















          DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:



           class GarageViewSet(viewsets.ModelViewSet):
          queryset = Garage.objects.all()
          serializer_class = GarageSerializer
          model = Garage

          @action(detail=False, methods=['put'])
          def update_car(self, request):
          ...
          # Use partial=True for partial updates.
          serializer = CarSerializer(data=request.data)

          # Validate data.
          serializer.is_valid(raise_exception=True)

          # Get validated data in dictionary format.
          validated_data = dict(list(serializer.validated_data.items()))

          # Update objects
          quertset.update(**validated_data)

          ...
          return Response(CarSerializer(queryset, many=True).data)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 2 at 22:55

























          answered Apr 2 at 20:32









          zeynelzeynel

          6954 silver badges12 bronze badges




          6954 silver badges12 bronze badges















          • Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

            – Joey Fran
            Apr 2 at 20:39











          • I has some doubts about your example... I update my question.

            – Joey Fran
            Apr 2 at 20:55











          • @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

            – zeynel
            Apr 2 at 21:04











          • My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

            – Joey Fran
            Apr 2 at 21:44











          • Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

            – zeynel
            Apr 2 at 22:25


















          • Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

            – Joey Fran
            Apr 2 at 20:39











          • I has some doubts about your example... I update my question.

            – Joey Fran
            Apr 2 at 20:55











          • @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

            – zeynel
            Apr 2 at 21:04











          • My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

            – Joey Fran
            Apr 2 at 21:44











          • Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

            – zeynel
            Apr 2 at 22:25

















          Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

          – Joey Fran
          Apr 2 at 20:39





          Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.

          – Joey Fran
          Apr 2 at 20:39













          I has some doubts about your example... I update my question.

          – Joey Fran
          Apr 2 at 20:55





          I has some doubts about your example... I update my question.

          – Joey Fran
          Apr 2 at 20:55













          @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

          – zeynel
          Apr 2 at 21:04





          @JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?

          – zeynel
          Apr 2 at 21:04













          My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

          – Joey Fran
          Apr 2 at 21:44





          My url example router.register(r"garage", GarageViewSet, base_name="garage"). I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'

          – Joey Fran
          Apr 2 at 21:44













          Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

          – zeynel
          Apr 2 at 22:25






          Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.

          – zeynel
          Apr 2 at 22:25





















          draft saved

          draft discarded















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406952%2fhow-better-way-to-create-a-function-to-pass-a-json-by-serializer-in-django-rest%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현