How to seed Django project ? – insert a bunch of data into the project for initialization

Similar to Rails, we also have option to seed the database. It is done using management commands. In one of your apps, use the following folder structure


this makes python seed available as a management command. I personally follow the following structure.

# <project>/<app>/management/commands/
from import BaseCommand
import random

# python seed --mode=refresh

""" Clear all data and creates addresses """
MODE_REFRESH = 'refresh'

""" Clear all data and do not create any object """
MODE_CLEAR = 'clear'

class Command(BaseCommand):
    help = "seed database for testing and development."

    def add_arguments(self, parser):
        parser.add_argument('--mode', type=str, help="Mode")

    def handle(self, *args, **options):
        self.stdout.write('seeding data...')
        run_seed(self, options['mode'])

def clear_data():
    """Deletes all the table data""""Delete Address instances")

def create_address():
    """Creates an address object combining different elements from the list""""Creating address")
    street_flats = ["#221 B", "#101 A", "#550I", "#420G", "#A13"]
    street_localities = ["Bakers Street", "Rajori Gardens", "Park Street", "MG Road", "Indiranagar"]
    pincodes = ["101234", "101232", "101231", "101236", "101239"]

    address = Address(
    )"{} address created.".format(address))
    return address

def run_seed(self, mode):
    """ Seed database based on mode

    :param mode: refresh / clear 
    # Clear data from tables
    if mode == MODE_CLEAR:

    # Creating 15 addresses
    for i in range(15):

In above structure you could, add custom modes, and seed accordingly. Also you could add additional management command arguments (e.g. number_of_addresses and pass it to run seed. the command would be python seed --mode=refresh --number_of_addresses=15).

Hope this helps. Cheers!

Leave a Comment