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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With