# Generated by Django 2.1.2 on 2018-10-18 02:18 from django.db import migrations, models import django.db.models.deletion import warnings def copy_reps_forward(apps, editor): Supplier = apps.get_model("procurement", "Supplier") Representative = apps.get_model("procurement", "Representative") suppliers = Supplier.objects.all() for sup in suppliers: name = sup.representative_name email = sup.representative_email rep = Representative(name=name, email=email, supplier=sup) rep.save() class ReverseMigrationDataLossWarning(UserWarning): def __init__(self, supplier, kept_rep, lost_reps): self.supplier = supplier self.kept_rep = kept_rep self.lost_reps = lost_reps @staticmethod def format_rep(rep): return '{} <{}>'.format(rep.name, rep.email) def __str__(self): return "Supplier {} has multiple representatives, only keeping {}. {} will be lost".format(self.supplier.name, self.format_rep(self.kept_rep), [self.format_rep(rep) for rep in self.lost_reps]) def copy_reps_rev(apps, editor): warnings.filterwarnings("always", category=ReverseMigrationDataLossWarning) Supplier = apps.get_model("procurement", "Supplier") Representative = apps.get_model("procurement", "Representative") suppliers = Supplier.objects.all() for sup in suppliers: reps = sup.representatives.all() if reps: keep = reps[0] if len(reps) > 1: lost = reps[1:] warnings.warn(ReverseMigrationDataLossWarning(sup, keep, lost)) sup.representative_name = keep.name sup.representative_email = keep.email sup.save() class Migration(migrations.Migration): dependencies = [ ('procurement', '0001_initial'), ] operations = [ migrations.CreateModel( name='Representative', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=255)), ('email', models.CharField(max_length=255)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='representative', name='supplier', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='representatives', to='procurement.Supplier'), ), migrations.RunPython(copy_reps_forward, copy_reps_rev), migrations.RemoveField( model_name='supplier', name='representative_email', ), migrations.RemoveField( model_name='supplier', name='representative_name', ), ]