DRF - How to get created object in CreateAPIView
Asked Answered
S

1

6

My goal very much resembles to what has been asked in this question but from the perspective of DRF, rather than forms.

So basically the question is, how can I get the newly created object in the following code snippet:

TestSerializer(serializers.ModelSerializer)
    class Meta:
        fields = '__all__'
        model = TestModel


class TestView(generics.CreateAPIView):
    serializer_class = TestSerializer

    def create(self, request, *args, **kwargs):
        response = super(TestView, self).create(request, *args, **kwargs)
        created_model_instance = .... ?
        print(created_model_instance.id)
        return response
Skyrocket answered 16/4, 2020 at 14:49 Comment(1)
still wondering if anyone got an answer to thisCockiness
P
2

You can override perform_create and use serializer.save to get the created object, like:

class TestView(generics.CreateAPIView):
    serializer_class = TestSerializer

    def perform_create(self, serializer):
        """Some doc here!"""
        obj = serializer.save()
        print(obj.id)
Pericles answered 8/11, 2020 at 17:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.