How to use dumpdata and loaddata for Django Groups with some permissions?

While writing testcases, I required fixtures or we can say json data to pre-populate database. I have a project which is using Django Groups and Permissions models.

Now, when I use command for dump data python dumpdata auth.Groups > fixtures/groups.json It will dump all data in groups.json file as show below.

Note: groups are added on the fly means when a specific registration form is triggered, it will create specific group and also add related related permissions in that group which i have defiend in code. But if group is already created, it will not try to create it again just simply assign that group to user.

enter image description here

Here, permissions are listed accourding to their id's.

Note: Some permissions are defaults and others are custom permissions defiend in models.

Now, I recreate database. Then, migrated with python migrate and created some users so that groups are created dynamically and permissions are assigned to that group which I mentioned above. Then, again used dump data command, this time ids are different. Also when I verified permissions in groups in django admin-panel, its showing different permission assigned to group to that of I coded.

From this, I assume that whenever I recreate database and call migrate command it will create all permissions but not in same manner always. So, single permission object can have different id each time i recreate database.

I have tried to edit groups.json file to change ids to their code name, but its showing error that list must contain int's.

Question: Is it possible that we have codenames of permissions in place of id's, so that every group will have expected permissions regardless of their id's. Also, while loading data, specific group will assign permissions to specific group only by their codename's. Is it even possible?

I found a solution for problems like that here . Here you can see the concept of natural keys. (in your case for Permissions) You can find that natural key in Django's PermissionManager provided by django’s default django.contrib.auth.models

class PermissionManager(models.Manager):
   use_in_migrations = True
   def get_by_natural_key(self, codename, app_label, model):
       return self.get(
               app_label, model

So simply you can use dumpdata --natural-foreign instead of just dumpdata to get data permission’s natural key instead of ids.

Back to Top