How to use make delete request of generic viewset without sending the pk

722 Views Asked by At

I am using django in the backend and react native in the frontend, I have a generic viewset with destroy, create mixins. In my use case, I make a post request when the user is logged in and then delete the same instance when he logged out. The problem is I don't know the pk of the created instance to send it in the delete request.

Is there a way to know the pk of the created model instance to use it then in the delete request?

NB: the model pk is automatically generated in Django, not a created field. The view is

class DeviceViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,
                         mixins.DestroyModelMixin, viewsets.GenericViewSet):
    serializer_class = DeviceSerializer
    queryset = Device.objects.all()
class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device 
        fields = '__all__'

1

There are 1 best solutions below

3
Risadinha On

As your data seems to be something that lives during the lifetime of the user session, the session sounds like a good place to store it.

On login for example, you could store the pk in the session:

# once the user is logged in and you have created this obj
obj = ThePersonalizedModel.objects.create(....)
request.session['personalized_obj_pk'] = obj.pk

and then whenever you need to delete it, and before the session expires:

delete_pk = request.session['personalized_obj_pk']

See https://docs.djangoproject.com/en/4.0/topics/http/sessions/#session-serialization for more infos on sessions.