如何在Django中删除ManyToMany字段的实例

时间:2017-12-03 08:25:54

标签: python django

我正在尝试删除Django中的ManyToMany字段的实例。 我尝试了这个,但它不起作用:

act = Activity.objects.get(pk=pk)
act.save()
attendee, _ = Attendee.objects.get_or_create(student=request.user)
**act.attendee.delete(attendee)**
return...

这个想法是在给定主键的情况下删除特定活动的参加者。

这些是我的模特:

class Attendee(models.Model):
student = models.ForeignKey(User, related_name="attendee")

class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)

1 个答案:

答案 0 :(得分:0)

要删除ManyToMany关系,请使用remove()而不是delete。

act.attendee.remove(attendee)

另外,我建议更改命名约定以提高可读性,

class Activity(models.Model):
    attendees = models.ManyToManyField(Attendee, related_name="activities", null=True, blank=True)

因此删除逻辑

act.attendees.remove(attendee)

您也可以使用反向关系删除

attendee.activities.remove(act)