Hi Prabhu, You are correct about how to fix the error you're seeing, but I think you're confused about why you're seeing it. As with all relationships, an object in a many-to-many relationship must have a primary key value before you can point a foreign key value at it from another table.
When you say: group = Group() group.name = name you are instantiating a new Group object and assigning its name attribute. This object does not get a primary key value until you call its save() method. (This is because the call to save() is the first time Django actually contacts the database to store your new Group object; before that point, it has no idea what the primary key value should be.) You can shorten the code to this: group = Group(name=name) group.save() In your code, you are then retrieving the new group object you just saved with this call: group = Group.objects.get(name=name) You don't need to do this; you can just use the same group object that you called save() on initially, and avoid a second database hit. Then, simply add the permissions to this group that you want: codename_list = [perm + '_' + model for model in models_list for perm in permission_list] permissions = Permission.objects.filter(codename__in=codename_list) for p in permissions: group.permissions.add(p) It shouldn't be necessary to call group.save() again at this point, because you're not actually modifying the group object; those calls to add() are storing the relationship between the group and each permission in a separate table. See: http://docs.djangoproject.com/en/dev/topics/db/queries/#saving-foreignkey-and-manytomanyfield-fields Hope that's helpful. Good luck! Richard On Jul 31, 5:52 am, prabhu S <prabhu...@gmail.com> wrote: > Hi All, > > When I try to create a Group (django.contrib.auth.models.Group) > dynamically, I get the below error. > > 'Group' instance needs to have a primary key value before a many-to- > many relationship can be used. > > This is because I am trying to add permissions to the group object and > trying to save every thing in one shot. As a work around to this > problem, I am doing an intermediate save and reload of Group object, > which seems to work fine. > > Is there a logical reason behind this error? Is this something > fixable? > > Regards, > Prabhu > P.S: Exact source code here > -http://github.com/prabhu/invoicy/blob/3f32fff86b806bc0b769de6de7dbe04... --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---