How to add multiple objects to ManyToMany relationship at once in Django ?

To add on, If you want to add them from a queryset
Example
# Returns a queryset
permissions = Permission.objects.all()

# Turns it into a list
permissions = list(permissions)

# Add the results to the many to many field (notice the *)

group = MyGroup.objects.get(name='test')

group.permissions.add(*permissions)
 
 
 
If you want to add a queryset to a many to many field first change it into a list and add it as positional arguments using *
Example
# Returns a queryset
permissions = Permission.objects.all()

# Add the results to the many to many field (notice the *)

group = MyGroup.objects.get(name='test')

group.permissions.add(*permissions)
 

No comments:

Post a Comment