当先锋百科网

首页 1 2 3 4 5 6 7

restframework中常用的modelviewset使用patch方法时只能对单个数据进行修改,可以通过拓展mixin实现

安装:

pip3 install https://github.com/chibisov/drf-extensions/archive/master.zip

views中添加ListUpdateModelMixin

from rest_framework_extensions.mixins import ListUpdateModelMixin

class UserViewSet(ListUpdateModelMixin, viewsets.ModelViewSet):
    serializer_class = UserSerializer

请求头中添加

X-BULK-OPERATION: ture

patch中为批量修改的参数

{"email_provider": "google"}

批量部分更新示例-设置每个用户的email_provider为谷歌,如果邮件以gmail.com结尾

# Request
PATCH /users/?email__endswith=gmail.com HTTP/1.1
Accept: application/json
X-BULK-OPERATION: true

{"email_provider": "google"}

# Response
HTTP/1.1 204 NO CONTENT
Content-Type: application/json; charset=UTF-8