【发布时间】:2013-11-27 11:43:44
【问题描述】:
我有以下型号:
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/
这将删除 current 收藏中的所有其他歌曲(这很好:)),但是当我尝试将现有歌曲添加到 current 收藏时它会告诉我一个错误:
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/
它会毫无问题地添加歌曲...
我可以使用序列化器作为字段从 current 和 saved 等集合中添加和删除歌曲吗?
【问题讨论】:
标签: python django django-rest-framework