13

I have a model which has has an primary key id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False).

When a PUT request is sent to the resource's endpoint /api/v1/resource/<id>.json I would like to create a new resource with the supplied id if the resource does not already exist.

Note: I'm using a ModelViewSet with a ModelSerializer

What is the most elegant way of doing this?

Daniel van Flymen
  • 10,931
  • 4
  • 24
  • 39

1 Answers1

13

I ended up overriding the get_object() method in my ModelViewSet:

class ResourceViewSet(viewsets.ModelViewSet):
    """
    This endpoint provides `create`, `retrieve`, `update` and `destroy` actions.
    """
    queryset = Resource.objects.all()
    serializer_class = ResourceSerializer

    def get_object(self):
        if self.request.method == 'PUT':
            resource = Resource.objects.filter(id=self.kwargs.get('pk')).first()
            if resource:
                return resource
            else:
                return Resource(id=self.kwargs.get('pk'))
        else:
            return super(ResourceViewSet, self).get_object()

Perhaps there's a more elegant way of doing this?

Daniel van Flymen
  • 10,931
  • 4
  • 24
  • 39
  • 4
    The issue with this is that it doesn't check for the create permission. I believe you should inherit from this mixin: https://gist.github.com/tomchristie/a2ace4577eff2c603b1b – Natim Mar 28 '18 at 15:02