views:

236

answers:

1
     for u in Users.objects.all():

      for g in u.group.all():
       if g not in Groups.objects.filter(domain__user=u.id):
       u.group.filter(id=g.id).delete()

How do I delete the entries in relationship table. In this case I have a many to many relationship between Groups and Users. The delete statement in the above code deletes the group from the Groups table. I just want to delete the relationship between the user and the group from the Users_group table. How do I do this.

Thanks

+3  A: 

The key to thinking about this problem is to realize that u.group is a manager, just as Groups.objects is a manager (by default the former is a subclass of the latter). Most operations that you call on u.group will affect the entire Group table (with the possibility that it first filters down to objects related to u). That means that, assuming g is related to u,

u.group.filter(id=g.id).delete()

should work the same as

Groups.objects.filter(id=g.id).delete()

In both cases, .filter() returns a queryset (completely naive with respect to u) and .delete() deletes all members.

The good news is that u.group should be a ManyRelatedManager, meaning that there will be additional methods available for it. For many examples, check here. The one that should fit your scenario:

u.group.remove(g)
David Berger
QuerySets have a .delete() method that deletes all the members of the QuerySet in a single SQL query.
Carl Meyer
Of course. Thanks!
David Berger