Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing initial data for models - Django

I want to enter default values in Django Models. For example, I have created one Role Model

class Role(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=100)

    class Meta:
        verbose_name = _('role')
        verbose_name_plural = _('roles')
        db_table = "role"

    def __str__(self) : 
        return self.name

I want to enter default values whenever I am migrating - makemigrations and migrate.

Example data should be entered -

name - Super Admin
Description - This is Super Admin
name - Admin
Description - This is Admin
name - Manager
Description - This is Manager

This will help reduce the amount of manual work I need to perform.. Thank you.

like image 593
Cipher Avatar asked Jan 26 '23 15:01

Cipher


1 Answers

I found a good way to do it. First we create a JSON file using the below line. Note - role is the app's name.

python3 manage.py dumpdata --format=json role > initial_role_data.json

After running the above commands it will create a file named initial_role_data.json which will have data something like this:

[
   {
      "model":"role.role",
      "pk":1,
      "fields":{
         "name":"Super Admin",
         "description":"This is Super Admin"
      }
   },
   {
      "model":"role.role",
      "pk":2,
      "fields":{
         "name":"Admin",
         "description":"This is Admin"
      }
   },
]

Note I have data already inside my database table. You can create a json file similar to above manually if needed.

Once the json file is generated we will load the data:

python3 manage.py loaddata initial_role_data.json 
like image 72
Cipher Avatar answered Jan 29 '23 04:01

Cipher