from django.db import migrations, models


def forwards_fill_club_id(apps, schema_editor):
    Model = apps.get_model('shop', 'DianpuShangpinShenheShezhi')
    # 历史全局单例 → 归到星阙 xq；若已有多行则只保留一条
    rows = list(Model.objects.all().order_by('id'))
    if not rows:
        return
    keep = rows[0]
    keep.club_id = keep.club_id or 'xq'
    keep.save(update_fields=['club_id'])
    for extra in rows[1:]:
        extra.delete()


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0003_zhi_kan_shenhe'),
    ]

    operations = [
        migrations.AddField(
            model_name='dianpushangpinshenheshezhi',
            name='club_id',
            field=models.CharField(
                db_index=True, default='xq', max_length=16, verbose_name='所属俱乐部',
            ),
        ),
        migrations.RunPython(forwards_fill_club_id, noop_reverse),
        migrations.AlterField(
            model_name='dianpushangpinshenheshezhi',
            name='club_id',
            field=models.CharField(
                db_index=True, default='xq', max_length=16, unique=True,
                verbose_name='所属俱乐部',
            ),
        ),
    ]
