41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
# Data migration: 从 Factory.short_name 的唯一值创建 Brand,并回填 Material.brand
|
||
|
||
from django.db import migrations
|
||
|
||
|
||
def forwards(apps, schema_editor):
|
||
Factory = apps.get_model('factory', 'Factory')
|
||
Brand = apps.get_model('brand', 'Brand')
|
||
Material = apps.get_model('material', 'Material')
|
||
|
||
short_names = (
|
||
Factory.objects
|
||
.exclude(short_name__isnull=True)
|
||
.exclude(short_name='')
|
||
.values_list('short_name', flat=True)
|
||
.distinct()
|
||
)
|
||
for sn in short_names:
|
||
Brand.objects.get_or_create(name=sn)
|
||
|
||
for brand in Brand.objects.all():
|
||
Material.objects.filter(factory__short_name=brand.name).update(brand=brand)
|
||
|
||
|
||
def backwards(apps, schema_editor):
|
||
# schema migration 回滚时会删掉 Material.brand 字段,这里无需操作
|
||
pass
|
||
|
||
|
||
class Migration(migrations.Migration):
|
||
|
||
dependencies = [
|
||
('material', '0007_add_brand_fk'),
|
||
('factory', '0004_rename_brand_to_short_name'),
|
||
('brand', '0001_initial'),
|
||
]
|
||
|
||
operations = [
|
||
migrations.RunPython(forwards, backwards),
|
||
]
|