DRF manymany字段在创建对象时得到错误



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

{
"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)

我在这里做错了什么?

我也遇到过类似的问题。执行以下操作来解决问题

  1. 安装drf-writable-nested withpip install drf-writable-nested
  2. 像这样重写序列化器
# --- 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调用。你应该可以走了。

要了解更多信息,请参阅此repo的README

当前,您可能会发送带有body的请求,例如

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

由于categories是一个多对多关系,它期望得到一个id列表,

试一试:

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

问题出在序列化器上,而您的序列化器是只读的,因此serializer.save()不起作用。

为了改变这种行为,您需要覆盖序列化器方法:create()和update(),或者/和save()。

查看此文档了解实现细节:https://www.django-rest-framework.org/api-guide/serializers/#saving-instances

相关内容

  • 没有找到相关文章

最新更新