Reputation: 183
I have a list of users and an auth group called 'group1'. These users are created through the bulk_create
method in Django. Now I need to add all these users to group 'group1'.
I can achieve this with a for loop like:
group1 = Groups.objects.get(name='group1')
for user in users:
group1.user_set.add(user)
but I am wondering if there are any easy and better ways without using the for loop.
Upvotes: 5
Views: 3113
Reputation: 308839
The add()
method accepts a list of objects:
group1 = Groups.objects.get(name='group1')
group1.user_set.add(*users)
This is slightly tidier, but I'm not sure you'll notice any difference in performance.
See the docs on many-to-many relationships for more info.
Upvotes: 9