Search code examples
djangodjango-rest-frameworkdjango-rest-viewsets

DRF Viewset - Do not create but return if object already exists


Is it possible to override the create of a Viewset to first check if an object exists and, if so, return that object rather than creating it?

Specifically, in my viewset, I have overriden the create function as follows:

try:
    item = Item.objects.get(recipe__id=self.request.data['recipe'])
except Item.DoesNotExist:
    serializer.save(owner=self.request.user)

Any ideas how I can pass the item back? Currently this just spits back the input. Even if I serialize and return the item, this does not seem to work as below:

try:
    item = Item.objects.get(
        recipe__id=self.request.data['recipe'])
    serializer = UserItemSerializer(item)
    return Response(serializer.data, status=status.HTTP_201_CREATED)
except Item.DoesNotExist:
    serializer.save(owner=self.request.user)

Solution

  • their is a function

    instance , created = Item.objects.get_or_create(parameter)
    

    this will get the object if exist or create the object if it doesn't exist, this will return two variable 1st one (in this case "instance " ) will be the object it does not matter it create and already exits, you will get the object for sure and the 2nd variable (in this "created ") will be a Boolean value , to identify if object is created or already exist . it will be True if object is created and false if object already exits . but you will get the object in 1st variable whether it created or exist .