2013-11-27 56 views
4

我有以下型號:更新M2M不能使用串行作爲字段時

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 

的問題: 我不能添加一首歌曲(即使它已經存在於DB)任何的(當前保存,什麼永遠),我只能刪除它。

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."]}]} 

BUT!如果我刪除串行領域:

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/ 

它增加了沒有任何問題的歌曲...

我可以從收藏品中添加和刪除歌曲像當前保存使用串行的領域?

回答

7

當然可以。你需要設置allow_add_removeTrueread_onlyFalse

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

注意,當前實現嵌套的序列化器都從數據庫中刪除整個宋對象,不僅關係。

+1

這是行不通的。現在我得到以下錯誤:'不能添加「:實例在數據庫」default「上,值在數據庫」None「'上。我假設Django在添加與Computer實例的多對多關係之前試圖保存Project實例。 –

相關問題