Custom function which performs create and update on DRF modelViewSet

后端 未结 2 921
不知归路
不知归路 2021-01-13 19:08

Hi there I want to create a custom method in a modelviewset which needs to perform a save and an update logic in a single post request.

Here is my

相关标签:
2条回答
  • 2021-01-13 19:23

    Well, from the comments, it looks like you want to update some unrelated model when you create your breeding model. This should be easy.

    class BreedingViewSet(viewsets.ModelViewSet):
        queryset = Breeding.objects.all()
        serializer_class = BreedingSerializer
    
        def create(self, request):
            # do your thing here
            return super().create(request)
    
    0 讨论(0)
  • 2021-01-13 19:43

    Use this to create or update using POST

    class BreedingViewSet(viewsets.ModelViewSet):
        queryset = Breeding.objects.all()
        serializer_class = BreedingSerializer
    
    
        def get_object(self):
            if self.action == 'create':
                queryset = self.filter_queryset(self.get_queryset())
                filter_kwargs = {self.lookup_field: self.request.data.get('id')}
                obj = get_object(queryset, **filter_kwargs)
                self.check_object_permissions(self.request, obj)
                return obj
            else:
                return super(BreedingViewSet, self).get_object()
    
        def create(self, request, *args, **kwargs):
            if request.data.get('id'):
                return super(BreedingViewSet, self).update(request, *args, **kwargs)
            else:
                return super(BreedingViewSet, self).create(request, *args, **kwargs)
    
    0 讨论(0)
提交回复
热议问题