# Add Soft Delete to a Django REST Framework API

Yes. An agent adds a deleted_at field and manager to the user model, a delete service that also revokes tokens, a delete endpoint and tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-soft-delete/django-rest-framework/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the model, its services and its API before adding a field. In a project shaped like HackSoftware/Django-Styleguide-Example, `requirements/base.txt` pins `Django` 5.2.7, `djangorestframework` 3.16.1, `drf-jwt` 1.19.2, `django-filter` 25.2 and `django-structlog` 9.1.1, and `requirements/local.txt` adds `pytest` 8.4.2 with `pytest-django` 4.11.1, `mypy` 1.18.2 with `django-stubs` and `djangorestframework-stubs`, and `ruff` 0.14.0. `users/models.py` defines `BaseUser` on the `BaseModel` from `common/models.py`, which gives it `created_at` and `updated_at`, with `email` as the `USERNAME_FIELD`, `is_active`, `is_admin`, a `jwt_key` UUID, and a `BaseUserManager` whose `create_user` calls `full_clean()` before saving. `users/services.py` has `user_create` and `user_update`, the latter built on `model_update` from `common/services.py`; `users/selectors.py` has `user_list` through `BaseUserFilter` on `id`, `email` and `is_admin`, and `user_get` through `get_object`. `users/apis.py` exposes list, create, detail and update as `APIView` classes with nested serializers, and `users/urls.py` maps them to `""`, `create/`, `<int:user_id>/` and `<int:user_id>/update/`. There is no delete anywhere, and the migrations stop at `0003_baseuser_jwt_key`.

The agent adds `deleted_at`, a nullable indexed `DateTimeField`, to `BaseUser`, with migration `0004_baseuser_deleted_at`. It writes a `BaseUserQuerySet` with `alive()` and `deleted()` and makes `BaseUser.objects` return alive users while `BaseUser.all_objects` returns everyone, keeping `create_user` and `create_superuser` on the manager so `createsuperuser` still works. Because Django's authentication backend looks users up through the default manager, a deleted user can no longer log in through `authentication/apis.py` without any change there.

In `users/services.py` it adds `user_delete(*, user)` under `@transaction.atomic`: it sets `deleted_at` to `timezone.now()`, sets `is_active` to `False`, and rotates `jwt_key`, because `drf-jwt` signs each user's tokens with that key through the project's `JWT_GET_USER_SECRET_KEY` setting, so every token already issued stops verifying at once. A matching `user_restore` clears the two fields. `users/apis.py` gets `UserDeleteApi`, a `POST` on `<int:user_id>/delete/` in the project's style of `POST` for state changes, answering `204` or `404` through `user_get`, and `users/urls.py` gets the route. `user_list` keeps returning alive users; a `deleted` filter on `BaseUserFilter` lets an admin list the others. `users/admin.py` adds `deleted_at` to `list_display`, `list_filter` and `readonly_fields`.

Tests follow `users/tests/services/test_user_create.py`: a `TestCase` per service. `test_user_delete.py` asserts the timestamp, the inactive flag, the rotated `jwt_key`, that `BaseUser.objects` no longer returns the user while `all_objects` does, and that `user_restore` reverses it; an API test asserts the `204`, the `404` on a second delete, and that the detail endpoint now answers `404`. Before pushing the agent runs what `.github/workflows/django.yml` runs: `ruff check .`, `mypy --config mypy.ini styleguide_example/` and `pytest`, plus `./manage.py makemigrations --check` to confirm the one new migration is complete.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add soft delete for users to this Django REST Framework project and open a pull request. Read requirements/base.txt, requirements/local.txt, styleguide_example/common/models.py, common/services.py, users/models.py, users/services.py, users/selectors.py, users/filters.py, users/apis.py, users/urls.py, users/admin.py, users/tests/services/test_user_create.py, authentication/services.py, config/django/base.py, mypy.ini, pytest.ini and .github/workflows/django.yml first. Add a nullable indexed deleted_at DateTimeField to BaseUser with migration 0004. Add a queryset with alive() and deleted(), make BaseUser.objects return alive users and BaseUser.all_objects return everyone, keeping create_user and create_superuser working. Add user_delete(*, user) in users/services.py under transaction.atomic that sets deleted_at, sets is_active False and rotates jwt_key so drf-jwt tokens stop verifying, and user_restore that reverses it. Add UserDeleteApi as a POST on <int:user_id>/delete/ answering 204 or 404 via user_get, add a deleted filter to BaseUserFilter, and show deleted_at in the admin's list_display, list_filter and readonly_fields. Add users/tests/services/test_user_delete.py and an API test in the existing TestCase style covering the fields, the two managers, restore, the 204, the 404 on repeat, and the detail endpoint answering 404. Run ruff check ., mypy --config mypy.ini styleguide_example/, pytest and ./manage.py makemigrations --check, and put the output in the pull request. Do not hard delete anything and do not change the email uniqueness constraint.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `users/migrations/0004_baseuser_deleted_at.py` and `users/tests/services/test_user_delete.py`, and changes `users/models.py`, `services.py`, `selectors.py`, `filters.py`, `apis.py`, `urls.py` and `admin.py`. The description shows the `pytest` summary with the new tests, clean `ruff` and `mypy` runs, the `makemigrations --check` result, and the generated migration's operations.

On a repository with this `Django` workflow, the pull request runs the Docker Compose job and the plain job, each with `ruff`, `mypy` and `pytest`, so the new typed manager and service are checked under `django-stubs` on the pull request itself.

A reviewer checks that no selector or admin query bypasses the alive manager by accident, that rotating `jwt_key` is what they want for a deleted account, since it also ends that user's sessions on every device, and that keeping the unique `email` means a deleted address cannot register again until it is restored. Then they decide whether other models in the project need the same queryset, which the pull request keeps to `BaseUser`.

## Run it on every new model that needs soft delete

The same request applies to any model in the project. Send one `POST /o/{org}/sessions` per model, naming its app in `input`, and each run reads that model's services, selectors and admin before writing the queryset, so a model without a token key gets a delete service without the rotation step, and a model with foreign keys gets a note on what still references its rows.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn finishes, with the `session_url` to read the pull request link from, so a handler on your server can post it where that app's owners review.

## Why run it on Rush?

Soft delete is a change to what every query means, and the mistakes are in the places you did not look: an admin page that still lists deleted rows, a token that still verifies, a `get_object` that still finds the row. The agent runs the project's `pytest`, `mypy` with Django stubs and `ruff` in its sandbox and keeps the output in the run's record, so the pull request shows the managers behaving under test rather than describing them.

The project's CI builds a Docker Compose stack to run the same checks, which is slow on a laptop. In Rush the agent runs them in its own sandbox before pushing, so the pull request opens green, and the same request body applies to every Django REST Framework service a team owns.

## Frequently asked questions

### Why rotate jwt_key on delete?

The project signs each user's tokens with that user's `jwt_key` through `drf-jwt`, which is how `auth_logout` already ends sessions. Rotating it on delete means a token issued before the delete fails verification, so a deleted user is logged out everywhere without a blacklist.

### Will deleted users still show up in the admin?

The admin uses the model's default manager, so deleted users disappear from the change list by default. The pull request adds `deleted_at` to `list_filter`, and a reviewer can ask for the admin to use `all_objects` with the filter instead if they want deleted rows visible.

### Can a deleted email address register again?

Not until the user is restored: the unique constraint on `email` is kept, and `create_user` runs `full_clean()`, which reports the clash. The pull request says so, and names the partial unique constraint to add if that behaviour should change.

### Why POST instead of DELETE for the endpoint?

The project's update endpoint is a `POST` on `<id>/update/`, and the pull request follows that convention with `<id>/delete/`. If you prefer `DELETE` on the detail route, say so in `input` and the agent adds a `delete` method to `UserDetailApi` instead.

## More Django REST Framework jobs

- [Add Throttling to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-throttling/django-rest-framework/)
- [Turn Sentry Errors Into Fix Pull Requests for a Django REST Framework API](https://getrush.ai/run/fix-sentry-errors/django-rest-framework/)
- [Migrate from drf-jwt to SimpleJWT in a Django REST Framework App](https://getrush.ai/run/migrate-to-simplejwt/django-rest-framework/)

## The same job on other stacks

- [Add Soft Delete to a Drizzle Schema](https://getrush.ai/run/add-soft-delete/drizzle/)
- [Add Soft Delete to a Fastify API from a Linear Issue](https://getrush.ai/run/add-soft-delete/fastify/)
- [Add Soft Deletes to a Filament Resource](https://getrush.ai/run/add-soft-delete/filament/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
