|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Generated by Django 1.10.5 on 2017-02-28 10:46 |
| 3 | +from __future__ import unicode_literals |
| 4 | + |
| 5 | +from django.db import migrations |
| 6 | +from collections import Counter |
| 7 | + |
| 8 | +import debug # pyflakes:ignore |
| 9 | + |
| 10 | +def repair_primary(apps, schema_editor): |
| 11 | + Person = apps.get_model('person','Person') |
| 12 | + Email = apps.get_model('person','Email') |
| 13 | + for p in Person.objects.all(): |
| 14 | + primary = p.email_set.filter(primary=True).first() |
| 15 | + if primary and not primary.active: |
| 16 | + #debug.show("['removing primary',primary.address,p.name]") |
| 17 | + primary.primary = False |
| 18 | + primary.save() |
| 19 | + new_primary = p.email_set.filter(active=True).order_by("-time").first() |
| 20 | + if new_primary: |
| 21 | + #debug.show("['adding primary',new_primary.address,p.name]") |
| 22 | + new_primary.primary = True |
| 23 | + new_primary.save() |
| 24 | + for p_id in [x for x in Counter(Email.objects.filter(primary=True).values_list('person',flat=True)).items() if x[1]>1]: |
| 25 | + for e in Email.objects.filter(person_id=p_id,primary=True)[1:]: |
| 26 | + #debug.show("['removing extra primary', e.address, e.person.name]") |
| 27 | + e.primary = False |
| 28 | + e.save() |
| 29 | + |
| 30 | +def do_nothing(apps, schema_editor): |
| 31 | + pass |
| 32 | + |
| 33 | +class Migration(migrations.Migration): |
| 34 | + |
| 35 | + dependencies = [ |
| 36 | + ('person', '0014_auto_20160613_0751'), |
| 37 | + ] |
| 38 | + |
| 39 | + operations = [ |
| 40 | + migrations.RunPython(repair_primary,do_nothing) |
| 41 | + ] |
0 commit comments