Wednesday 25 May 2022

Django migrations seed

 



https://stackoverflow.com/questions/51577441/how-to-seed-django-project-insert-a-bunch-of-data-into-the-project-for-initi

<project>/<app>/management/commands/seed.py

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

# <project>/<app>/management/commands/seed.py
from django.core.management.base import BaseCommand
import random

# python manage.py 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'])
        self.stdout.write('done.')


def clear_data():
    """Deletes all the table data"""
    logger.info("Delete Address instances")
    Address.objects.all().delete()


def create_address():
    """Creates an address object combining different elements from the list"""
    logger.info("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(
        street_flat=random.choice(street_flats),
        street_locality=random.choice(street_localities),
        pincode=random.choice(pincodes),
    )
    address.save()
    logger.info("{} address created.".format(address))
    return address

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

    :param mode: refresh / clear 
    :return:
    """
    # Clear data from tables
    clear_data()
    if mode == MODE_CLEAR:
        return

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




!! NOTE: using json file is ok, but library has not been updated for a long time,

https://medium.com/@ardho/migration-and-seeding-in-django-3ae322952111


Simple 1 : 

manually create a json file via build in django cmd, then use 


python manage.py loaddata <file>


simple file can be created using 


For example, we want to create two Admin object and make the fixture file. So make it a regular model for admin, then we could run dumpdata command. First, create the object of the model (we’ll use Django shell, just choose which one is most comfortable). (Admin model in admin_birpen app)

python3 manage.py shell
>>> from admin_birpen.models import Admin
>>> Admin(pk=1, username="@adminPPL").save()
>>> Admin(pk=2, username="@adminPacil").save()

Then we can dump the created data in JSON file a.k.a. the fixture file in seed/0008_Admin.json with 4 indentation space.

<admin_birpen> is the app name

python3 manage.py dumpdata admin_birpen --indent 4 > seed/0008_Admin.json

Or generate complex json file using

django-seed plugin

pip install django-seed

For installation, just run pip install django-seed. More documentation about django-seed visit this link. So I will simulate generate the fixture for the model Pengumuman. Long short story, Pengumuman model has more than 13 fields with quite a lot of model dependencies.

So how do we generate the fixture? Simple, just run python3 manage.py seed pengumuman --number=2, so from this command, we will generate 2 object models in the pengumuman application. This command is not to generate fixture directly, but rather to make the object directly inputted to the database. So how do we generate the fixture? As previously explained, we can use dumpdata command!


No comments:

Post a Comment