django休息视图中的部分更新

时间:2016-11-16 05:28:33

标签: python django-rest-framework

我有使用用户个人资料的视图。其中实现put和delete方法。如何添加补丁方法或使用方法仅更新一个字段(创建/更新头像字段)?

views.py:

from rest_framework import permissions
from rest_framework.generics import RetrieveAPIView
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.serializers import ValidationError

from djangorestframework_camel_case.parser import CamelCaseJSONParser

from api.models import User
from api.permissions import IsOwnerOrReadOnly
from api.auth.serializers import username_validation
from .serializers import AccountSerializer


class AccountAPIView(RetrieveAPIView, UpdateModelMixin, DestroyModelMixin):
    queryset = User.objects.all()
    permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticated)
    serializer_class = AccountSerializer
    parser_classes = (MultiPartParser, FormParser, CamelCaseJSONParser)


    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        user = self.request.user
        new_username = self.request.data.get('username', None)
        if new_username and user.username != new_username:
            try:
                username_validation(new_username)
            except ValidationError as error:
                Response(str(error), status=status.HTTP_400_BAD_REQUEST)

        return self.update(request, *args, **kwargs)

serializers.py:

from rest_framework import serializers

from api.models import User, Album, Photo, Like

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'avatar', 'bio', 'location')
        read_only_fields = ('id',)

2 个答案:

答案 0 :(得分:0)

添加

partial=True

in serializer enble partial edits

答案 1 :(得分:0)

最简单的解决方案就是使用与put和delete方法相同的原理:

def patch(self, request, *args, **kwargs):
        self.usernameCheck()
        return self.partial_update(request, *args, **kwargs)