Early on in the development of my Django project, I had to rebuild the database a thousand times! To make my life easier, I created Django Management Commands to recreate data from these Management Commands. As you can imagine, to recreate all my models like: a DoriDoro
instance and several instances of Achievements
, Degree
, Fact
, Hobby
, Job
, Language
, Reference
and SocialMedia
.
Here is an example of a Management Command:
# doridoro/management/commands/create_links.py
from django.core.management.base import BaseCommand
from django.db import IntegrityError, transaction
from projects.models import Link
class Command(BaseCommand):
help = "This command creates all Job instances for DoriDoro."
def handle(self, *args, **options):
try:
links = [
{
"title": "Epic Events",
"legend": "Project 12 of OpenClassrooms Python Path",
"origin": Link.GITHUB,
"platform": Link.OPENCLASSROOMS,
"url": "https://github.com/DoriDoro/EpicEvents",
},
{
"title": "Orange Country Lettings",
"legend": "Project 13 of OpenClassrooms Python Path",
"origin": Link.GITHUB,
"platform": Link.OPENCLASSROOMS,
"url": "https://github.com/DoriDoro/OC_lettings",
},
{
"title": "Django Portfolio",
"legend": "Django Portfolio",
"origin": Link.GITHUB,
"platform": Link.PERSONAL_PROJECT,
"url": "https://github.com/DoriDoro/django_portfolio",
},
]
if Link.objects.exists():
self.stdout.write(
self.style.WARNING("These instances of Link exists already!")
)
return
with transaction.atomic():
for link in links:
Link.objects.create(**link)
self.stdout.write(
self.style.SUCCESS("Instances of Link successfully created!")
)
except IntegrityError:
self.stdout.write(
self.style.WARNING("These Link instances exists already!")
)
except Exception as e:
self.stdout.write(self.style.ERROR(f"An unexpected error occurred: {e}"))
You may ask, why not use django-admin dumpdata
to reuse the data from my database? Quite simply, I changed the model attributes and the data structure was no longer the same. So I needed another way to recreate all the data (which is a lot of content) every time my model structure changed.