Mohit Harshan
Mohit Harshan

Reputation: 1986

populate table with initial data

I want to prepopulate some tables with initial data and also modify certian fields. Im currently doing this by writing custom management commands and populating database using python manage.py . Recently i read about fixtures and came to know its used for the same purpose .Which is the right way to do this and why or why not this should be done using the management commands?

Example code in management/commands/init_test_data.py

class Command(BaseCommand):
    help = 'Initializes test data'

    @transaction.atomic
    def handle(self, *args, **kwargs):
        __location__ = os.path.realpath(os.path.join(
            os.getcwd(), os.path.dirname(__file__)))
        fname = os.path.join(__location__, 'init_test_data.json')
        with open(fname) as f:
            parsed = json.load(f)
        for tenant in parsed.get('tenants'):
            self.create_tenant(tenant)

    def create_tenant(self, tenant):
        tenant_obj = Tenant()
        tenant_obj.name = tenant["name"]
        tenant_obj.subdomain = tenant["subdomain"]
        tenant_obj.identifier = tenant["identifier"]
        tenant_obj.save()
        for org in tenant.get('organisations'):
            self.create_org(tenant_obj, org)
        admin_email = "sysadmin_" + tenant_obj.name + "@exza.com"
        admin_roles = ["tenant_system_admin", "tenant_admin"]
        self.create_user(None, tenant_obj, admin_email, admin_roles, True, True)
        for asset in tenant.get('assets'):
            self.create_dummy_asset(tenant_obj, asset.get('name'))

Upvotes: 0

Views: 990

Answers (1)

Krukas
Krukas

Reputation: 677

Fixtures is indeed the way to go to set some initial data. If you want to perform some more complex operations you can use custom migrations (https://docs.djangoproject.com/en/2.2/howto/writing-migrations/)

Upvotes: 2

Related Questions