django-ninja-ulid
Accept and return ULIDs as 26-character strings in Django Ninja APIs.
Django Ninja infers a UUID type for python-ulid-django's ULIDField. This package provides explicit ULID validation and serialization, plus response schemas that preserve ordinary UUID fields.
ApiULIDvalidates ULID strings, gives you aulid.ULIDin Python, and serializes to an uppercase string.create_ulid_response_schemabuilds flat response schemas from Django models. Foreign keys and many-to-many relations return IDs rather than nested objects.related_idsconverts related model instances to their primary keys for hand-written schemas.
ID generation and storage remain with python-ulid and python-ulid-django.
Installation
For ApiULID, use the base installation. For Django model integration, use the orm extra:
pip install django-ninja-ulid
pip install "django-ninja-ulid[orm]"
This alpha release supports Python 3.12–3.14 and the dependency ranges below. See Compatibility for the tested versions.
| Dependency | Version constraint |
|---|---|
| Django | >=5.2.18,<6.2,!=6.1.0,!=6.1.1 |
| Django Ninja | >=1.7.1,<2 |
| Pydantic | >=2.13.5,<3 |
| python-ulid | >=4.0.1,<5 |
| python-ulid-django | >=1.6.0,<2 (with orm) |
Check these constraints against your project's dependencies before installing. The base installation includes Django and Ninja; importing ApiULID does not load them or require Django settings. The orm extra adds python-ulid-django.
Quick start
In an existing Django project, create catalog/api.py in your app. The example uses catalog as the app name and config as the project package; use your own names if they differ.
# catalog/api.py
from ninja import NinjaAPI, Schema
from django_ninja_ulid import ApiULID
api = NinjaAPI()
class Identifier(Schema):
id: ApiULID
@api.post("/echo", response=Identifier)
def echo(request, payload: Identifier):
return payload
Add the API to your project's URL configuration, keeping any existing routes:
# config/urls.py
from django.urls import path
from catalog.api import api
urlpatterns = [path("api/", api.urls)]
Start the development server with python manage.py runserver, then send a lowercase ULID:
curl http://127.0.0.1:8000/api/echo \
-H 'Content-Type: application/json' \
-d '{"id":"01arz3ndektsv4rrffq69g5fav"}'
The response is HTTP 200 with an uppercase ULID:
{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV"}
An invalid value such as "invalid" or 42 produces HTTP 422. The endpoint's payload.id is a ULID object; the response schema converts it to a string. You can also use ApiULID for path and query parameters, as the next example shows for a path parameter.
Django model responses
Install the orm extra and add your app (catalog here) to INSTALLED_APPS. Define a model with a ULID primary key and an optional foreign key:
# catalog/models.py
import uuid
from django.db import models
from ulid import ULID
from ulid_django.models import ULIDField
class Owner(models.Model):
id = ULIDField(primary_key=True, default=ULID, editable=False)
class Item(models.Model):
id = ULIDField(primary_key=True, default=ULID, editable=False)
public_uuid = models.UUIDField(default=uuid.uuid4)
name = models.CharField(max_length=100)
owner = models.ForeignKey(Owner, null=True, on_delete=models.SET_NULL)
Replace catalog/api.py from the quick start with this version. Keep the same URL configuration. Import django_ninja_ulid.orm after Django has initialized, such as from your app's API module loaded by the URL configuration.
# catalog/api.py
from django.shortcuts import get_object_or_404
from ninja import NinjaAPI
from django_ninja_ulid import ApiULID
from django_ninja_ulid.orm import create_ulid_response_schema
from .models import Item
api = NinjaAPI()
ItemOut = create_ulid_response_schema(
Item,
name="ItemOut",
fields=["id", "public_uuid", "name", "owner"],
)
@api.get("/items/{item_id}", response=ItemOut)
def get_item(request, item_id: ApiULID):
return get_object_or_404(Item, pk=item_id)
Choose the exposed fields explicitly with a non-empty fields list. The helper overrides ULID fields and relations to ULID primary keys; all other fields retain Ninja's normal types.
Create the tables and a sample item:
python manage.py makemigrations catalog
python manage.py migrate
python manage.py shell -c 'from catalog.models import Item; print(Item.objects.create(name="example").pk)'
Request /api/items/<printed-id> while the development server is running. The response has this shape (the generated IDs will differ):
{
"id": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"public_uuid": "8f14e45f-ceea-467f-a0e6-4b6f8b8a8c1d",
"name": "example",
"owner": null
}
If an owner is assigned, owner contains its ULID string. The foreign key is read through owner_id, without fetching the owner object. With by_alias=True on the route, the output key is owner_id instead of owner; see the alias limitation below.
Many-to-many relations
For a Tag model with a ULID primary key, add tags = models.ManyToManyField(Tag) to Item, run migrations, and include "tags" in ItemOut's fields. The response contains a list of ULID strings, or [] when no tags are assigned.
Replace the detail endpoint's lookup with get_object_or_404(Item.objects.prefetch_related("tags"), pk=item_id). For lists of items, use prefetch_related("tags") on the queryset to avoid a separate tag query for each item. The schema helper does not optimize queries automatically.
| Selected field | Response behavior |
|---|---|
ULIDField or ULID foreign key with null=False |
Key is always included; value is not null |
ULIDField or ULID foreign key with null=True |
Key is always included; value may be null |
| Many-to-many relation to a ULID primary key | Key is always included; list may be empty, never null |
| Non-ULID field | Ninja's usual behavior |
Hand-written schemas
To control the schema yourself, use ApiULID explicitly. Put this schema in catalog/schemas.py, import it in catalog/api.py with from .schemas import ManualItemOut, and set the route's response=ManualItemOut:
# catalog/schemas.py
from ninja import ModelSchema
from pydantic import Field
from django_ninja_ulid import ApiULID
from .models import Item
class ManualItemOut(ModelSchema):
id: ApiULID
owner: ApiULID | None = Field(..., alias="owner_id")
class Meta:
model = Item
fields = ["public_uuid", "name"]
For many-to-many fields, related_ids converts a Manager, QuerySet, or list of model instances into a list of primary keys. Place this definition before ManualItemOut in the same module, loaded after Django initialization through your API module:
# catalog/schemas.py (before ManualItemOut)
from typing import Annotated
from pydantic import BeforeValidator
from django_ninja_ulid import ApiULID
from django_ninja_ulid.orm import related_ids
RelatedULIDs = Annotated[list[ApiULID], BeforeValidator(related_ids)]
After adding tags to the model, declare tags: RelatedULIDs alongside id and owner in ManualItemOut. List only the fields Ninja should infer from the model (public_uuid and name) in Meta.fields.
Validation and serialization
- HTTP input must be a 26-character ASCII ULID string. Lowercase is accepted and normalized to uppercase.
- The first character must be
0–7. CharactersI,L,O, andU(including lowercase) are rejected, not treated as aliases. - Numbers, booleans, null, objects, and arrays are rejected. Use
ApiULID | Nonewhen null is allowed. - Python validation also accepts existing
ulid.ULIDinstances. Validated attributes areULIDobjects; serialization, includingmodel_dump(), produces uppercase strings. - Invalid request input produces HTTP 422 in Ninja. Direct Pydantic validation raises
ValidationError.
You can use the type without configuring Django:
from pydantic import TypeAdapter
from ulid import ULID
from django_ninja_ulid import ApiULID
adapter = TypeAdapter(ApiULID)
value = adapter.validate_python("01arz3ndektsv4rrffq69g5fav")
assert isinstance(value, ULID)
assert adapter.dump_python(value) == "01ARZ3NDEKTSV4RRFFQ69G5FAV"
Why not plain ModelSchema?
We tested plain schemas with Django Ninja 1.7.1 and python-ulid 4.0.1.
ULIDFieldinherits fromUUIDField, so Ninja infers a UUID type. A 26-character ULID request value fails UUID validation with HTTP 422; a model response containing a ULID fails response validation with HTTP 500.- Declaring the raw
ulid.ULIDtype in a hand-written schema avoids UUID inference, but its output can fail JSON encoding with aTypeErrorand HTTP 500. - Registering a global replacement with
register_field("UUIDField", ...)also changes ordinary UUID fields.
Error responses can change with dependency updates. Posting {"id": {}} to an endpoint that declares id: ulid.ULID returns HTTP 500 with python-ulid 4.0.1 and HTTP 422 with 4.2.0.
ApiULID handles validation and serialization explicitly. create_ulid_response_schema applies it only to the selected ULID fields and relations.
Scope and limitations
create_ulid_response_schema generates flat response schemas for python-ulid-django fields. It does not generate request or PATCH schemas, nested responses, or schemas for other ULID field libraries.
An empty fields list, a foreign key targeting a non-primary-key to_field, reverse relations, OneToOneField, and composite primary keys raise ValueError when the schema is created.
Two known OpenAPI limitations:
- In Ninja 1.7.1, reusing one schema across routes with different
by_aliassettings causes the last registered route to determine the shared OpenAPI component's field names. HTTP responses remain correct. Create a schema with a distinctnamefor each output format. - The OpenAPI pattern accepts lowercase in responses as well as requests. Actual serialized output is always uppercase.
Compatibility
| Component | Tested versions |
|---|---|
| Python | 3.12 / 3.13 / 3.14 |
| Django | 5.2.18 / 6.0.10 / 6.1.3 |
| Databases | SQLite / PostgreSQL 18.6 |
| Django Ninja | 1.7.1 and the latest 1.x |
| Pydantic | 2.13.5 and the latest 2.x |
| python-ulid | 4.0.1 and the latest 4.x |
| python-ulid-django | 1.6.0 and the latest 1.x |
CI runs four representative Python, Django, and database combinations on pull requests. Pushes to main, manual runs, weekly runs, and releases cover all 18. Two additional SQLite jobs test the lowest compatible dependencies on Python 3.12 and the latest compatible releases on Python 3.14, so the latest releases are checked at least weekly. See compatibility and verification details (Japanese).
Versioning and contributing
The public API consists of ApiULID, create_ulid_response_schema, and related_ids. During 0.x, breaking changes use a minor release (for example, 0.1 → 0.2); compatible fixes use a patch release.
- Changelog (Japanese)
- Versioning policy (Japanese)
- Development and bug reports (Japanese)
- Report an issue
License
Metadata
Release files for django-ninja-ulid 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_ninja_ulid-0.1.2.tar.gz | 107.2 kB | With provenance | Details for django_ninja_ulid-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_ninja_ulid-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for django_ninja_ulid-0.1.2-py3-none-any.whl |
Total release size: 116.7 kB
Release files / django_ninja_ulid-0.1.2.tar.gz
| Download URL | django_ninja_ulid-0.1.2.tar.gz |
|---|---|
| Size | 107.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d66a0d0662775955cfdd2b1271cba7bde03aad1b1adb4948e0951a710a3a1d04
|
|
BLAKE2b-256 checksum How to use checksums |
bde7aed115f22e524007ff8439fafcd54afb42822530ac4d8c07cfcee92f3c2b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / django_ninja_ulid-0.1.2-py3-none-any.whl
| Download URL | django_ninja_ulid-0.1.2-py3-none-any.whl |
|---|---|
| Size | 9.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4b577da95ba539da7ea761f9a070c2c476a867a644511b8899c6104f1a1c1c07
|
|
BLAKE2b-256 checksum How to use checksums |
1bdf11b4444ca78e9dc79fb33f9551890434029bccc6b2e77e34ad9b2b9cfea2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for django-ninja-ulid 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for django_ninja_ulid-0.1.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.