views:

123

answers:

2

According to an example at http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships 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.
+2  A: 

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)
Nick Craig-Wood
+2  A: 

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").

shylent