from django.db import migrations def crear_importadores_desde_pedimentos(apps, schema_editor): Pedimento = apps.get_model('customs', 'Pedimento') Importador = apps.get_model('customs', 'Importador') Organizacion = apps.get_model('organization', 'Organizacion') rfcs_orgs = Pedimento.objects.values_list('contribuyente', 'organizacion_id').distinct() for rfc, org_id in rfcs_orgs: if rfc and not Importador.objects.filter(rfc=rfc).exists(): organizacion = Organizacion.objects.get(id=org_id) if org_id else None Importador.objects.create(rfc=rfc, nombre='', organizacion=organizacion) class Migration(migrations.Migration): dependencies = [ ('customs', '0009_importador'), ] operations = [ migrations.RunPython(crear_importadores_desde_pedimentos), ]