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__'
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:
and then whenever you need to delete it, and before the session expires:
See https://docs.djangoproject.com/en/4.0/topics/http/sessions/#session-serialization for more infos on sessions.