Django Rest Framework POST Update if existing or create

前端 未结 8 1816
余生分开走
余生分开走 2020-12-13 09:24

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

8条回答
  •  抹茶落季
    2020-12-13 09:48

    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)
    

提交回复
热议问题