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
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)
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)