Django REST framework post array of objects

后端 未结 5 629
挽巷
挽巷 2020-12-16 14:43

I am using Django REST framework for API and Angular SPA with Restangular to communicate with the API. Sometimes, I have to add more than one object using the API and I thin

5条回答
  •  [愿得一人]
    2020-12-16 15:26

    I am not sure if the problem still exist. But the solution suggested by fiver did not work for me. What works for me is overriding the get_serializer method ONLY.

    def get_serializer(self, instance=None, data=None,
                        files=None, many=True, partial=False):
        return super(ViewName, self).get_serializer(instance, data, files,
                                                        many, partial)
    

    If you will notice I am setting default many=True in arguments of get_serializer. Apart from that nothing is required. Overridng of create method is also not required.

    Also if you are defining the pre_save and post_save method in the views, expects the list(iterable) as the argument(as you are posting the list) of method not just a single object.

    def post_save(self, objects, *args, **kwargs):
        """
        In the post_save, list of obj has been created
        """
        for obj in objects:
            do_something_with(obj)
    

提交回复
热议问题