'How to use make delete request of generic viewset without sending the pk
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__'
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Risadinha |
