from django.http.response import Http404
class UpdateNonExistentMixin(object):
"""
drf views mixin for update an non-existent object(e.g. update or create then update).
"""
def get_object(self):
try:
obj = super().get_object()
except Http404:
# update even not exists
if self.action in ['update', 'partial_update']:
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
obj = self.get_serializer_class().Meta.model(**{self.lookup_field: self.kwargs[lookup_url_kwarg]})
else:
raise Http404
return obj