0
私はユーザーのプロフィールを扱うためのビューを持っています。 putとdeleteメソッドを実装するものどのように私はパッチメソッドを追加するか、または(アバターフィールドの作成/更新)1つのフィールドのみを更新するためのメソッドを使用できますか?django rest viewの部分的な更新
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',)