1

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__'

Menna Magdy
  • 355
  • 1
  • 2
  • 14

1 Answers1

0

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.

Risadinha
  • 16,058
  • 2
  • 88
  • 91
  • Thank you for your answer, but I have a question I don't create the object from the backend it is only created when a post request from the frontend is made, so how to save obj.pk once post request is done? I also edited the question with my serializer – Menna Magdy Feb 03 '22 at 18:05
  • Your "post request from the frontend" is still received in the backend and the backend will have to act on it. Without more of your code it is very difficult to give you a specific answer, so I'm mostly guessing and interpreting on what you might actually need. – Risadinha Feb 03 '22 at 18:14
  • I get it but how to access the pk from the backend, I mean should I overwrite the create function of the view? – Menna Magdy Feb 03 '22 at 18:36