Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

I want to enter default values in Django Models. Like i have create 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 me from doing manual work.

1 Answer

0 votes
by (25.1k points)

I found the way to do it. First we create a JSON file using below line. Note - role is app 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 some 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 json file similar to above manually also.

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

python3 manage.py loaddata initial_role_data.json

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...