Custom Function Which Performs Create And Update On Drf Modelviewset
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 breeding.viewsets.py class Breedi
Solution 1:
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)
Solution 2:
Use this to create or update using POST
classBreedingViewSet(viewsets.ModelViewSet):
queryset = Breeding.objects.all()
serializer_class = BreedingSerializer
defget_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:
returnsuper(BreedingViewSet, self).get_object()
defcreate(self, request, *args, **kwargs):
if request.data.get('id'):
returnsuper(BreedingViewSet, self).update(request, *args, **kwargs)
else:
returnsuper(BreedingViewSet, self).create(request, *args, **kwargs)
Post a Comment for "Custom Function Which Performs Create And Update On Drf Modelviewset"