简体   繁体   English

如何在不发送 pk 的情况下使用通用视图集的删除请求

[英]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.我在后端使用 django 并在前端做出本机反应,我有一个带有销毁的通用视图集,创建 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.问题是我不知道创建实例的 pk 以在删除请求中发送它。

Is there a way to know the pk of the created model instance to use it then in the delete request?有没有办法知道创建的 model 实例的 pk 以便在删除请求中使用它?

NB: the model pk is automatically generated in Django, not a created field.注意:model pk 是在 Django 中自动生成的,而不是创建的字段。 The view is观点是

class DeviceViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,
                         mixins.DestroyModelMixin, viewsets.GenericViewSet):
    serializer_class = DeviceSerializer
    queryset = Device.objects.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.由于您的数据似乎存在于用户 session 的生命周期中,因此 session 听起来是存储它的好地方。

On login for example, you could store the pk in the session:例如,在登录时,您可以将 pk 存储在 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:然后每当您需要删除它时,在 session 到期之前:

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.有关会话的更多信息,请参阅https://docs.djangoproject.com/en/4.0/topics/http/sessions/#session-serialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM