Django关联模型更新:查询user_id为3的用户Profile更新路径
答案
情况1:使用DRF默认路由生成规则
你当前用默认ModelViewSet+自动路由生成的规则下,UserProfile资源的更新路径需要携带profile_id(UserProfile表的主键),对应HTTP方法为PUT(全量更新)或PATCH(部分字段更新)。
比如user_id=3的用户对应的profile_id为10的话,更新路径为:
PUT/PATCH /user/profile/10/
这种方式的缺点是你需要先查询到用户对应的profile主键才能发起更新,使用不够方便。
情况2:调整ViewSet配置实现直接通过user_id更新
你可以修改UserProfileViewSet的配置,指定以关联的user_id作为查询字段,不用传profile_id就可以直接更新对应用户的资料:
- 给
UserProfileViewSet添加如下配置:
class UserProfileViewSet(viewsets.ModelViewSet): # 原有其他配置不变,新增下面两行 lookup_field = "user_id" queryset = UserProfile.objects.all()
- 调整后user_id=3的用户的profile更新路径直接为:
PUT/PATCH /user/profile/3/
额外注意事项
- 如果你只允许用户更新自己的资料,还需要在ViewSet中添加权限校验,避免越权修改其他用户的资料
- 提交请求时如果有上传图片字段(thumbnail),需要将请求头的
Content-Type设为multipart/form-data
内容的提问来源于stack exchange,提问作者user11751463
相关产品推荐
相关产品推荐

