python - 将序列化程序用作字段时无法更新 m2m

标签 python django django-rest-framework

我有以下模型:

class Song(models.Model):
    name = models.CharField(max_length=64)

    def __unicode__(self):
        return self.name

class UserProfile(AbstractUser):
    current = models.ManyToManyField(Song, related_name="in_current", blank=True)
    saved = models.ManyToManyField(Song, related_name="in_saved", blank=True)
    whatever = models.ManyToManyField(Song, related_name="in_whatever", blank=True)

    def __unicode__(self):
        return self.get_username()

和以下序列化器:

class SongSerializer(serializers.ModelSerializer):
    class Meta:
        model = Song

class UserProfileSongsSerializer(serializers.ModelSerializer):
    current = SongSerializer(many=True)
    saved = SongSerializer(many=True)
    whatever = SongSerializer(many=True)

    class Meta:
        model = UserProfile
        fields = ("id", "current", "saved", "whatever")

并且我这样使用 UpdateAPIView:

class UserProfileSongsUpdate(generics.UpdateAPIView):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSongsSerializer

问题: 我无法将歌曲(即使它已经存在于数据库中)添加到任何(当前,保存,等等),我只能删除它。

curl -X PUT -d '{"current": [{"id": 1, "name": "sialalalal"}, {"id": 2, "name": "imissmykitty"}], "saved": [{"id": 3, "name": "kittyontheroad"}], "whatever": []}' -H "Content-Type:application/json" localhost:8000/userprofile/1/songs/update/

这将删除当前 收藏中的所有其他歌曲(这很好 :)),但是当我尝试将现有歌曲添加到当前 收藏时它会告诉我一个错误:

curl -X PUT -d '{"current": [{"id": 1, "name": "sialalalal"}, {"id": 2, "name": "imissmykitty"}, {"id": 7, "name": "vivalakita"}], "saved": [{"id": 3, "name": "kittyontheroad"}], "whatever": []}' -H "Content-Type:application/json" localhost:8000/userprofile/1/songs/update/

我得到:

{"current": [{}, {}, {"non_field_errors": ["Cannot create a new item, only existing items may be updated."]}]}

但是!如果我删除序列化程序字段:

class UserProfileSongsSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ("id", "current", "saved", "whatever")

我这样做:

curl -X PUT -d '{"current": [1, 2, 7], "saved": [3], "whatever": []}' -H "Content-Type:application/json" localhost:8000/userprofile/1/songs/update/

它添加歌曲没有任何问题...

我可以使用序列化器作为字段在当前已保存等集合中添加和删除歌曲吗?

最佳答案

是的,你可以。您需要将 allow_add_remove 设置为 True 并将 read_only 设置为 False:

current = SongSerializer(many=True, allow_add_remove=True, read_only=False)

请注意,嵌套序列化程序的当前实现将从 DB 中删除整个 Song 对象,而不仅仅是关系。

关于python - 将序列化程序用作字段时无法更新 m2m,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20241542/

相关文章:

python - 这个 selenium firefox 配置文件将文件下载到自定义文件夹有什么问题?

python - 循环创建一个元组

python - Django Rest Framework : Create/Update by id, 输出字典

python - Django Rest Framework ViewSet 的其他 View

python - UnicodeDecodeError : 'utf-8' when debugging Python files in PyCharm Community

python - pandas中按列值触发结果

reactjs - AWS Cognito 与 django 休息框架 react js?

json - Django:相互嵌套序列化器

Python 多进程错误

django - 聚合分组注释