1

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)
NickP
  • 1,354
  • 1
  • 21
  • 51

2 Answers2

1

This will return a queryset

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, ]
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.all()

So to return just 1, pass a kwarg (probably pk) and return something different from get_queryset()

HenryM
  • 5,557
  • 7
  • 49
  • 105
1

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 .

biswa1991
  • 530
  • 3
  • 8