Skip to content

Upgrading to 1.4

Introduction

The 1.4 release includes a migration that adds and populates the prefix and hashed_key fields to API keys.

This document lists the steps necessary to upgrade from 1.3.x to 1.4.

Steps

1. Migrate the built-in API key model

The APIKey model can be migrated using the migration shipped with this package:

python manage.py migrate rest_framework_api_key

2. Migrate custom API key models (if applicable)

If you have a custom API key model deriving from AbstractAPIKey, you need to manually add the migration to your application.

  • Copy the migration script below to your app's migrations/ directory. Be sure to modify APP_NAME, MODEL_NAME and DEPENDENCIES as seems fit. You can name the migration script xxxx_prefix_hashed_key.py (replace xxxx with the next available migration ID).
# Generated by Django 2.2.2 on 2019-06-29 10:38

from django.db import migrations, models

APP_NAME = "rest_framework_api_key"
MODEL_NAME = "apikey"
DEPENDENCIES = [(APP_NAME, "0003_auto_20190623_1952")]


def populate_prefix_hashed_key(apps, schema_editor) -> None:  # type: ignore
    model = apps.get_model(APP_NAME, MODEL_NAME)

    for api_key in model.objects.using(
        schema_editor.connection.alias
    ).all():  # pragma: nodj22
        prefix, _, hashed_key = api_key.id.partition(".")
        api_key.prefix = prefix
        api_key.hashed_key = hashed_key
        api_key.save()


class Migration(migrations.Migration):
    dependencies = DEPENDENCIES

    operations = [
        migrations.AddField(
            model_name=MODEL_NAME,
            name="hashed_key",
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name=MODEL_NAME,
            name="prefix",
            field=models.CharField(max_length=8, unique=True, null=True),
        ),
        migrations.RunPython(populate_prefix_hashed_key, migrations.RunPython.noop),
        migrations.AlterField(
            model_name=MODEL_NAME,
            name="hashed_key",
            field=models.CharField(max_length=100, editable=False),
        ),
        migrations.AlterField(
            model_name=MODEL_NAME,
            name="prefix",
            field=models.CharField(max_length=8, unique=True, editable=False),
        ),
    ]
  • Apply the migration:
python manage.py migrate <my_app>