I am new to DRF. I read the API docs, maybe it is obvious but I couldn\'t find a handy way to do it.
I have an Answer object which has one-to-one relationship with a
A more generic answer, I think this should be in viewset instead of the serializer, because serializer need just serialize, nothing more.
This simulates conditions to update passing the id from request.data to kwargs, when if the instance doesn't exists, the UpdateModelMixin.update() raises an Http404 exception what is catched by except block and do a create().
from rest_framework.mixins import UpdateModelMixin
from django.http import Http404
class AnswerViewSet(UpdateModelMixin, ModelViewSet):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer
filter_fields = ("question", "answer")
update_data_pk_field = 'id'
def create(self, request, *args, **kwargs):
kwarg_field: str = self.lookup_url_kwarg or self.lookup_field
self.kwargs[kwarg_field] = request.data[self.update_data_pk_field]
try:
return self.update(request, *args, **kwargs)
except Http404:
return super().create(request, *args, **kwargs)