How to add multiple users to a single auth_group in Django
Asked Answered
B

1

5

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.

Bermuda answered 25/4, 2018 at 10:33 Comment(1)
Note that Django 1.8 is end-of-life and does not receive support updates, and that it does not officially support Python 3.6.Cammie
C
9

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.

Cammie answered 25/4, 2018 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.