DRF 更新嵌套字段

时间:2021-07-01 08:00:05

标签: python-3.x django-rest-framework

我正在尝试创建 API。我的目标是 CRUD。当我想更新它时,弹出消息“具有该用户名的用户已经存在。”和“具有此标题的类别已经存在。” 我不知道如何离开或更改现有用户、类别。

serializer.py

from rest_framework import serializers
from ..models import Rzeczy, Category, Mapa
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username')


class MapSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mapa
        fields = ('geolocation',)


class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ('id', 'title',)


class FindsSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    location = MapSerializer()
    user = UserSerializer()

    class Meta:
        model = Rzeczy
        fields = ('__all__')
        read_only_fields = ('user',)

views.py

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class FindsViewSet(viewsets.ModelViewSet):
    queryset = Rzeczy.objects.all()
    serializer_class = FindsSerializer

留言

HTTP 400 Bad Request
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "category": {
        "title": [
            "category with this title already exists."
        ]
    },
    "user": {
        "username": [
            "A user with that username already exists."
        ]
    }
}

0 个答案:

没有答案