from django.db import migrations def copy_tokens_to_apikeys(apps, schema_editor): """Carry every existing DRF authtoken over to a named ApiKey so keys issued before the multi-key feature keep authenticating (incl. the permanent test user and any deployed agents). Same key string -> no client reconfiguration.""" Token = apps.get_model("authtoken", "Token") ApiKey = apps.get_model("artifacts", "ApiKey") for token in Token.objects.all(): if ApiKey.objects.filter(key=token.key).exists(): continue api_key = ApiKey.objects.create(user_id=token.user_id, name="default", key=token.key) # created_at is auto_now_add, so set it after the fact to preserve the # original issue date (queryset.update bypasses auto_now_add). ApiKey.objects.filter(pk=api_key.pk).update(created_at=token.created) def noop(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ("artifacts", "0014_apikey"), ("authtoken", "0004_alter_tokenproxy_options"), ] operations = [ migrations.RunPython(copy_tokens_to_apikeys, noop), ]