根據一個example,我有三個型號:如何在Django的多對多關係中刪除中間模型的實例?
class User(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(User, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(User)
group = models.ForeignKey(Group)
date_joined = models.DateField()
添加成員的作品。但是,如何刪除單個成員資格實例 (用戶退出組),而不刪除用戶和組?
當我嘗試刪除這樣的:
u = User(request.user)
g = Group.objects.get(id=group_id, membership__user=u)
m = Membership(user=request.user, group=g)
m.delete()
我得到一個錯誤:
AssertionError at /groups/quit/1/
Membership object can't be deleted because its id attribute is set to None.