62 lines
2.1 KiB
Python
62 lines
2.1 KiB
Python
from django.db import migrations, models
|
|
|
|
|
|
def forwards(apps, schema_editor):
|
|
Dinosaur = apps.get_model('cards', 'Dinosaur')
|
|
# Constants must match those used in models at conversion time
|
|
SPEED_MAX_KMH = 60.0
|
|
WEIGHT_MAX_KG = 15000.0
|
|
HEIGHT_MAX_M = 12.0
|
|
|
|
for obj in Dinosaur.objects.all():
|
|
try:
|
|
# previous values were 0-100 percentages
|
|
old_speed = getattr(obj, 'speed', None)
|
|
old_weight = getattr(obj, 'weight', None)
|
|
old_height = getattr(obj, 'height', None)
|
|
if old_speed is not None:
|
|
new_speed = int(round(float(old_speed) / 100.0 * SPEED_MAX_KMH))
|
|
obj.speed = new_speed
|
|
if old_weight is not None:
|
|
new_weight = int(round(float(old_weight) / 100.0 * WEIGHT_MAX_KG))
|
|
obj.weight = new_weight
|
|
if old_height is not None:
|
|
new_height = round(float(old_height) / 100.0 * HEIGHT_MAX_M, 1)
|
|
# assign as string to avoid Decimal conversion issues
|
|
obj.height = new_height
|
|
obj.save(update_fields=['speed', 'weight', 'height'])
|
|
except Exception:
|
|
# skip errors during migration for safety; admins can fix manually
|
|
continue
|
|
|
|
|
|
def reverse(apps, schema_editor):
|
|
# Not reversible automatically
|
|
pass
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('cards', '0003_dinosaur_facts'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.AlterField(
|
|
model_name='dinosaur',
|
|
name='speed',
|
|
field=models.PositiveIntegerField(default=30, help_text='Speed in km/h'),
|
|
),
|
|
migrations.AlterField(
|
|
model_name='dinosaur',
|
|
name='weight',
|
|
field=models.PositiveIntegerField(default=1000, help_text='Weight in kg'),
|
|
),
|
|
migrations.AlterField(
|
|
model_name='dinosaur',
|
|
name='height',
|
|
field=models.DecimalField(default=1.5, max_digits=5, decimal_places=1, help_text='Height in metres'),
|
|
),
|
|
migrations.RunPython(forwards, reverse_code=migrations.RunPython.noop),
|
|
]
|