如何在Django多对多关系中删除中间模型的实例?

时间:2022-10-04 14:49:32

According to an example, I have three models:

根据一个例子,我有三个模型:

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()

Adding members works. But how do I delete a single Membership instance (a User quits a group), without deleting neither the User, nor the Group?

添加成员有效。但是,如何删除单个成员资格实例(用户退出组),而不删除用户和组?

When I try deleting it like this:

当我尝试删除它时:

    u = User(request.user)
    g = Group.objects.get(id=group_id, membership__user=u)
    m = Membership(user=request.user, group=g)
    m.delete()

I get an error:

我收到一个错误:

AssertionError at /groups/quit/1/

/ groups / quit / 1 /的AssertionError

Membership object can't be deleted because its id attribute is set to None.

无法删除成员资格对象,因为其id属性设置为None。

2 个解决方案

#1


17  

In the line

在线

m = Membership(user=request.user, group=g)

You created a new Membership you didn't fetch one from the database. That is why its id attribute is set to None.

您创建了一个未从数据库中获取的新成员资格。这就是为什么它的id属性设置为None。

Perhaps you meant

也许你的意思

m = Membership.objects.get(user=request.user, group=g)

#2


4  

This particular error is triggered by the fact, that your m instance of class Membership is unsaved, so its primary key is None. Apparently, it is impossible to delete such an unsaved instance (which makes sense, because there is nothing to "delete").

这个特定错误是由以下事实触发的:您的m类实例的成员身份未保存,因此其主键为None。显然,删除这样一个未保存的实例是不可能的(这是有道理的,因为没有什么可以“删除”)。

#1


17  

In the line

在线

m = Membership(user=request.user, group=g)

You created a new Membership you didn't fetch one from the database. That is why its id attribute is set to None.

您创建了一个未从数据库中获取的新成员资格。这就是为什么它的id属性设置为None。

Perhaps you meant

也许你的意思

m = Membership.objects.get(user=request.user, group=g)

#2


4  

This particular error is triggered by the fact, that your m instance of class Membership is unsaved, so its primary key is None. Apparently, it is impossible to delete such an unsaved instance (which makes sense, because there is nothing to "delete").

这个特定错误是由以下事实触发的:您的m类实例的成员身份未保存,因此其主键为None。显然,删除这样一个未保存的实例是不可能的(这是有道理的,因为没有什么可以“删除”)。