Thursday, September 26, 2019

Django Rest Framework mutilple update in ModelViewSet

Django Rest Framework mutilple update in ModelViewSet

It is required to receive a json to update several objects (N number of objects) by using a ModelViewSet that uses different serializers


viewsets.py
class ContractsViewSet(viewsets.ModelViewSet):
   serializer_class = ContractsSerializer (many=True)
   queryset = Contracts.objects.all()
   pagination_class = CustomPagination
   filter_backends = [filters.SearchFilter]
   search_fields = ['bundle','name']
    action_serializers = {
       'list': ContractsListSerializer,
       'retrieve': ContractsListSerializer,
       'partial_update':ContractsSerializer,
   }
   def get_serializer_class(self):
       try:
           return self.action_serializers [self.action]
       except (KeyError,AttributeError):
           return super().get_serializer_class()

 
serializers.py
class ContractsSerializer(serializers.ModelSerializer):
    class Meta:
       model = Contracts
       fields = ('id', 'name','bundle','state')
       extra_kwargs = {'name': {'required': False},'state': {'required': False}}



link code

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4a8b5dea-10df-40a3-bdb4-d28050850773%40googlegroups.com.

No comments:

Post a Comment