Reputation: 10993
In Django (when using django.contrib.auth) may I add a Group
to another Group
? Ie a a Group
be a member of another Group
?
If so how do I do this? I add User
s to a Group
using the user_set
, but from what I gather the default Group
model does not have a many to many to it self.
Docs: https://docs.djangoproject.com/en/1.7/topics/auth/default/#groups
Upvotes: 17
Views: 4265
Reputation: 6363
This can be done using django-groups-manager
:
The following is taken from the documentation. It shows creating a group called 'F.C. Internazionale Milan', then adding 'Staff' and 'Players' sub-groups, then finally adding members to those groups.
from groups_manager.models import Group, Member
fc_internazionale = Group.objects.create(name='F.C. Internazionale Milan')
staff = Group.objects.create(name='Staff', parent=fc_internazionale)
players = Group.objects.create(name='Players', parent=fc_internazionale)
thohir = Member.objects.create(first_name='Eric', last_name='Thohir')
staff.add_member(thohir)
palacio = Member.objects.create(first_name='Rodrigo', last_name='Palacio')
players.add_member(palacio)
Note that, although the django-group-manager
package appears to be actively maintained, this package is based on the django-mptt
package, which is marked as unmaintained on the GitHub project.
As mentioned in a previous comment, the django-mptt
package may also help implement this functionality.
The documentation provides an example that shows adding a parent
attribute to the Group
auth model.
https://django-mptt.readthedocs.io/en/latest/models.html#registration-of-existing-models
import mptt
from mptt.fields import TreeForeignKey
from django.contrib.auth.models import Group
# add a parent foreign key
TreeForeignKey(Group, on_delete=models.CASCADE, blank=True, null=True).contribute_to_class(Group, 'parent')
mptt.register(Group, order_insertion_by=['name'])
Upvotes: 3