from django.db import migrations, models
from django.db.models import Max


def _dedupe_duoci_fenhong(apps, schema_editor):
    DuociFenhong = apps.get_model('products', 'DuociFenhong')
    for row in DuociFenhong.objects.values(
        'club_id', 'huiyuan', 'yonghuid', 'cishu',
    ).annotate(max_id=Max('id')):
        DuociFenhong.objects.filter(
            club_id=row['club_id'],
            huiyuan=row['huiyuan'],
            yonghuid=row['yonghuid'],
            cishu=row['cishu'],
        ).exclude(id=row['max_id']).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('products', '0004_gsfenhong_club_id'),
    ]

    operations = [
        migrations.AddField(
            model_name='duocifenhong',
            name='club_id',
            field=models.CharField(db_index=True, default='xq', max_length=16, verbose_name='所属俱乐部'),
        ),
        migrations.RunPython(_dedupe_duoci_fenhong, migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='duocifenhong',
            unique_together={('club_id', 'huiyuan', 'yonghuid', 'cishu')},
        ),
    ]
