This is a more flexible way of seeding data 1. Create required directories and files $ mkdir testapp/management $ mkdir testapp/management/commands $ touch testapp/management/__init__.py $ touch testapp/management/commands/__init__.py 2. Write code that populates the db $ vi testapp/management/commands/populate_db.py from django.core.management.base import BaseCommand from testapp.models import Region from django.db import connection class Command(BaseCommand): args = '' help = 'Management script that populates the database with initial seed' def _truncate_region(self): cursor = connection.cursor() cursor.execute("TRUNCATE TABLE `testapp_region`") def _create_regions(self): regions = ( ('REG001', [ {"name": "vmk-4027","vlanId":4027,"usefor":["vsan","nfs"]}, {"name": "vmk-4028","vlanId":4028,"usefor":["traffic"]}, {"name": "vmk-102","vlanId":102,"usefor":["pub"]}, ]), ('REG002', [ {"name": "vmk-4029","vlanId":4029,"usefor":["vsan","nfs"]}, {"name": "vmk-4030","vlanId":4030,"usefor":["traffic"]}, {"name": "vmk-102","vlanId":103,"usefor":["pub"]}, ]), ) for item in regions: region = Region(name=item[0], vlans=item[1]) region.save() def handle(self, *args, **options): self._truncate_region() self._create_regions() 3. Execute the program $ python manage.py populate_db
7.26.2017
Django Data Seeding
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment