无法在指定中间模型的 ManyToManyField 上使用 remove()。

我按照文档了解如何在下面的 manytomanyfield 中删除一个项目,但它似乎不起作用,我收到了一个属性错误。remove 方法在没有中间模型的情况下工作得很好。


models.py


   class Song (models.Model):

        author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)

        timestamp= models.DateTimeField(auto_now_add=True, editable=False)

        songname = models.CharField(max_length=500, null=False, blank=False)

        tags = TaggableManager()


        def __str__(self):

            return self.songname


    class Playlist (models.Model):

        name = models.CharField(max_length=150, null=False, blank=False)

        author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)

        song = models.ManyToManyField(Song, through='Playlist_Activity')



    class Playlist_Activity(models.Model):

        song= models.ForeignKey(Song, on_delete=models.CASCADE)

        playlist= models.ForeignKey(Playlist, on_delete=models.CASCADE)

        timestamp= models.DateTimeField(auto_now_add=True, editable=False)


        class Meta:

            ordering = ('timestamp',)

Views.py


@login_required

def Playlist_Remove(request, id, P_id):

    p = Playlist.objects.get(id=P_id)

    s = p.song.get(id=id)    

    p.song.remove(s)

    return redirect('account')


紫衣仙女
浏览 82回答 1
1回答

MYYA

您可以删除中间实例:p = Playlist.objects.get(id=P_id)s = Song.objects.get(id=id)Playlist_Activity.objects.get(song=s, playlist=p).delete()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python