django DRF ManyToMany字段在创建对象时出错

gtlvzcf8  于 2023-04-13  发布在  Go
关注(0)|答案(3)|浏览(196)

我有一个Rant模型,使用ManyToManyFieldCategory链接到它。我已经序列化了它,但问题是这个错误:

{
  "categories": [
    "Expected a list of items but got type \"str\"."
  ]
}

这些是我的序列化器:

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"

class RantSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True)

    class Meta:
        model = Rant
        fields = ('rant', 'slug', 'categories')

我的post方法是这样的:

def post(self, request, format=None):
        serializer = RantSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我做错了什么?

jgwigjjp

jgwigjjp1#

我也遇到过类似的问题。请执行以下操作来解决您的问题
1.使用pip install drf-writable-nested安装drf-writable-nested
1.像这样重写序列化器

# --- snip ---
from drf_writable_nested.serializers import WritableNestedModelSerializer

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"

class RantSerializer(WritableNestedModelSerializer):
    categories = CategorySerializer(many=True)

    class Meta:
        model = Rant
        fields = ('rant', 'slug', 'categories')
# ---snip ----

这里的关键是导入和实现WritableNestedModelSerializer类。还要注意,serializers.ModelSerializer超类已经在序列化器上被替换,在那里你想做嵌套的有效载荷。
1.尝试执行API调用。应该可以了。
有关详细信息,请参阅此存储库的README here

nbysray5

nbysray52#

当前您可能会发送一个包含body的请求,如下所示:

{
    "rant": "This is my rant",
    "slug": "my-rant",
    "categories": 1
}

由于categories是一个ManyToMany关系,它需要一个id列表,
给予这个:

{
    "rant": "This is my rant",
    "slug": "my-rant",
    "categories": [1, 2, 3]
}
wko9yo5t

wko9yo5t3#

问题出在序列化器上,而你的序列化器是只读的,因此serializer.save()没有效果。
为了改变这种行为,需要覆盖serializer方法:create()和update(),或/和保存()。
有关实施详细信息,请查看此文档:https://www.django-rest-framework.org/api-guide/serializers/#saving-instances

相关问题