import django.db.models.deletion from django.db import migrations, models def create_materials_for_existing_fertilizers(apps, schema_editor): Fertilizer = apps.get_model('fertilizer', 'Fertilizer') Material = apps.get_model('materials', 'Material') FertilizerProfile = apps.get_model('materials', 'FertilizerProfile') for fertilizer in Fertilizer.objects.all(): material = Material.objects.create( name=fertilizer.name, material_type='fertilizer', maker=fertilizer.maker or '', stock_unit='bag', is_active=True, notes=fertilizer.notes or '', ) FertilizerProfile.objects.create( material=material, capacity_kg=fertilizer.capacity_kg, nitrogen_pct=fertilizer.nitrogen_pct, phosphorus_pct=fertilizer.phosphorus_pct, potassium_pct=fertilizer.potassium_pct, ) fertilizer.material = material fertilizer.save(update_fields=['material']) def reverse_migration(apps, schema_editor): Fertilizer = apps.get_model('fertilizer', 'Fertilizer') Fertilizer.objects.all().update(material=None) class Migration(migrations.Migration): dependencies = [ ('fertilizer', '0004_fertilizationplan_calc_settings'), ('materials', '0001_initial'), ] operations = [ migrations.AddField( model_name='fertilizer', name='material', field=models.OneToOneField( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='legacy_fertilizer', to='materials.material', verbose_name='資材マスタ', ), ), migrations.RunPython(create_materials_for_existing_fertilizers, reverse_migration), ]