Search code examples
djangodjango-modelsmany-to-many

How to remove a user from all ther groups they belong to in django model?


For instance, I have two model Group and OrganizationUser. members is a field in Group model which defines as

members=models.ManyToManyField('organizations.OrganizationUser', related_name="member_in_groups", blank=True)

that means a Group instance can have zero or multiple member and an OrganizationUser instance can be a member of zero or multiple Group

For an instance of OrganizationUser user1 I can do user1.member_in_groups.all() to access all the groups user1 is a member of. I want to remove user1 from all the groups user1 is a member of. I'm feeling iterating over the groups one by one and remove user1 isn't a right approach. What is the right way of doing so?


Solution

  • I have got the solution

    clear method should work in the scenario. user1.member_in_groups.clear() will clear the record of groups user1 member of also it will reflect on the other end of the relation, that means user1 will be removed from the groups user1 was a member of.