Skip to content

Instantly share code, notes, and snippets.

@adamJLev
Created December 22, 2015 19:37
Show Gist options
  • Save adamJLev/7e19e02880dd1e7bd5fa to your computer and use it in GitHub Desktop.
Save adamJLev/7e19e02880dd1e7bd5fa to your computer and use it in GitHub Desktop.
Django + MySQL script to prepare data for Strict mode
from django.core.management import BaseCommand
from django.db import transaction
from django.db.models import DateTimeField, DateField
from django.db.models.loading import get_models
class Command(BaseCommand):
help = """
One-time use script prepping for SQL strict mode.
Iterates through all models and fixes invalid date/datetime fields.
"""
def handle(self, *args, **options):
models = get_models()
affected_models = {}
# Figure out which model/fields need fixing
for model in models:
for field in model._meta.get_fields(include_parents=True, include_hidden=True):
if isinstance(field, (DateField, DateTimeField)):
affected_models.setdefault(model, []).append(field)
with transaction.atomic():
# Update data that needs to be fixed
for model, fields in affected_models.items():
self.stdout.write('About to check {} with fields {}'.format(model, fields))
for field in fields:
# Get all objects that need fixin'
manager = getattr(model, 'all_objects', model.objects)
if isinstance(field, DateTimeField):
self.stdout.write('About to process datetimefield {}'.format(field))
qs = manager.extra(where=["{} = '0000-00-00 00:00:00'".format(field.name)])
if qs.all():
self.stderr.write('-- Updating {} records with broken datetime'.format(len(qs.all())))
qs.all().update(**{field.name: '2013-01-01 00:00:00'})
elif isinstance(field, DateField):
self.stdout.write('About to process datefield {}'.format(field))
qs = manager.extra(where=["{} = '0000-00-00'".format(field.name)])
if qs.all():
self.stderr.write('-- Updating {} records with broken datetime'.format(len(qs.all())))
qs.all().update(**{field.name: '2013-01-01'})
else:
self.stderr.write('-- Ignoring {}.{}'.format(model, field))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment