django 发送请求时,ManyToManyField类型的字段不保存数据,DRF

hgqdbh6s  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(148)

基本上,我会执行类似于“Archive of Our Own”的操作,但不会保存或保存工作,但不会保存“多对多”字段数据
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字段,就可以正常工作。
当我在www.example.com上写这篇文章时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不添加到字段中
当我在www.example.com上写这篇文章时serializers.py

fandoms = FandomSerializer(many=True)
  pairings = PairingSerializer(many=True)
  characters = HeroSerializer(many=True)
  tags = TagSerializer(many=True)

Postman

{
   "message": {
      "fandoms": [
         "This field is required."
      ],
      "pairings": [
         "This field is required."
      ],
      "characters": [
         "This field is required."
      ],
      "tags": [
         "This field is required."
      ]
   }
}
hfyxw5xn

hfyxw5xn1#

您可以将嵌套序列化程序的字段设置为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}
        ...
    }
    ...

参考:(需要)

相关问题