python – 使用序列化程序作为字段时无法更新m2m
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用序列化程序作为字段时无法更新m2m,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2380字,纯文字阅读大概需要4分钟。
内容图文
![python – 使用序列化程序作为字段时无法更新m2m](/upload/InfoBanner/zyjiaocheng/804/fc99817d44484ec8bfb51518ee8197ad.jpg)
我有以下型号:
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全部内容,希望文章能够帮你解决python – 使用序列化程序作为字段时无法更新m2m所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。