Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete an instance of an intermediate model in a Django Many-to-many relationship?

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/

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

like image 443
ria Avatar asked Nov 30 '22 06:11

ria


1 Answers

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.

Perhaps you meant

m = Membership.objects.get(user=request.user, group=g)
like image 140
Nick Craig-Wood Avatar answered Dec 06 '22 08:12

Nick Craig-Wood