基本上,我做的事情就像‘我们自己的存档’,我没有保存或保存工作,但是ManyToMany字段数据没有保存
views.py
if request.method == 'POST':
serializer = FanficSerializerCreate(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'fanfic': serializer.data}, status = status.HTTP_201_CREATED)models.py
class Fanfic(models.Model):
...
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
fandoms = models.ManyToManyField(Fandom)
pairings = models.ManyToManyField(Pairing)
characters = models.ManyToManyField(Hero)
tags = models.ManyToManyField(Tag)
....serializer.py
class FanficSerializerCreate(ModelSerializer):
fandoms = FandomSerializer(many=True, read_only=True)
pairings = PairingSerializer(many=True, read_only=True)
characters = HeroSerializer(many=True, read_only=True)
tags = TagSerializer(many=True, read_only=True)
class Meta:
model = Fanfic
fields = ['id', 'user', 'title', 'fandoms', 'pairings', 'characters', 'translate', 'categories', 'end', 'relationships', 'tags', 'description', 'note', 'i_write_for', 'created', 'updated']我认为问题是在另一节的序列化程序中,例如,添加一个具有相同视图代码的字符,但是模型中没有多个manytomanyfield字段就可以了。
当我在serializers.py中写这个的时候
fandoms = FandomSerializer(many=True, read_only=True)
pairings = PairingSerializer(many=True, read_only=True)
characters = HeroSerializer(many=True, read_only=True)
tags = TagSerializer(many=True, read_only=True)显示
{
"fanfic": {
"id": 4,
"user": 3,
"title": "Claimed",
"fandoms": [],
"pairings": [],
"characters": [],
"translate": "NO",
"categories": "M",
"end": "ENDED",
"relationships": "M/M",
"tags": [],
"description": "",
"i_write_for": "...",
"created": "2022-11-14T13:46:44.425693Z",
"updated": "2022-11-14T13:46:44.425693Z"
}
}id只是没有添加到字段中。
当我在serializers.py中写这个的时候
fandoms = FandomSerializer(many=True)
pairings = PairingSerializer(many=True)
characters = HeroSerializer(many=True)
tags = TagSerializer(many=True)邮递员
{
"message": {
"fandoms": [
"This field is required."
],
"pairings": [
"This field is required."
],
"characters": [
"This field is required."
],
"tags": [
"This field is required."
]
}
}发布于 2022-11-14 14:32:54
可以将嵌套序列化器的字段设置为required=False对该字段不需要的字段:
class FanficSerializerCreate(ModelSerializer):
fandoms = FandomSerializer(many=True, required=False)
...
class Meta:
model = Fanfic
...此外,您还可以为Meta类中的不同字段使用它:
class FanficSerializerCreate(ModelSerializer):
fandoms = FandomSerializer(many=True)
...
class Meta:
model = Fanfic
extra_kwargs = {
'fandoms': {'required': False}
...
}
...参考资料:(https://www.django-rest-framework.org/api-guide/fields/#required)
https://stackoverflow.com/questions/74432987
复制相似问题