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 or later and below 6.2 (except 6.1.0 and 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.
# 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
In catalog/models.py, define Tag before Item and give it the same ULID primary-key field as Owner. 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 |
Request schemas
Define create and PATCH request bodies with Ninja's Schema. For the Item model above, add this create endpoint to catalog/api.py, using the ItemOut response schema that includes tags.
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404
from ninja import Schema, Status
from pydantic import Field
from django_ninja_ulid import ApiULID
from .models import Item, Owner, Tag
class CreateItem(Schema):
name: str = Field(max_length=100)
owner: ApiULID | None = None
tags: list[ApiULID] = Field(default_factory=list)
@api.post("/items", response={201: ItemOut})
@transaction.atomic
def create_item(request, payload: CreateItem):
owner = get_object_or_404(Owner, pk=payload.owner) if payload.owner is not None else None
tags = Tag.objects.in_bulk(payload.tags)
if any(tag_id not in tags for tag_id in payload.tags):
raise Http404("Tag not found")
item = Item.objects.create(name=payload.name, owner=owner)
item.tags.set(tags.values())
return Status(201, item)
Send this JSON body to POST /api/items, using IDs from your own Owner and Tag rows. The view returns the saved item with HTTP 201, or HTTP 404 if a referenced row is missing.
{
"name": "Desk",
"owner": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"tags": ["01ARZ3NDEKTSV4RRFFQ69G5FAW"]
}
You can omit owner or send null for an item without an owner. Omitting tags gives the item an empty tag list. In a PATCH view, check "owner" in payload.model_fields_set to distinguish an explicit null from an omitted field.
For a list of item IDs in a query string, use Query[list[ApiULID]]. Repeat the ids parameter for each ID, as in GET /api/items?ids=01arz3ndektsv4rrffq69g5fax&ids=01arz3ndektsv4rrffq69g5fay.
from ninja import Query
@api.get("/items", response=list[ItemOut])
def list_items(request, ids: Query[list[ApiULID]]):
return Item.objects.filter(pk__in=ids).prefetch_related("tags")
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.
# 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.
Each entry in Ninja's detail or Pydantic's ValidationError.errors() identifies the cause in its type field.
type |
Cause |
|---|---|
ulid_type |
A value other than a string or a Python ulid.ULID instance. |
ulid_length |
A string shorter or longer than 26 characters. ctx.actual_length gives the character count. |
ulid_parsing |
A 26-character string with a character outside the ASCII Crockford Base32 alphabet or a first character outside 0–7. |
For example, posting a 25-character id to /api/echo returns HTTP 422 with this body.
{
"detail": [{
"type": "ulid_length",
"loc": ["body", "payload", "id"],
"msg": "ULID must be 26 characters long (got 25)",
"ctx": {"actual_length": 25}
}]
}
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"
Troubleshooting
Importing django_ninja_ulid.orm loads Ninja's settings. With the orm extra installed and no Django settings configured, python -c "import django_ninja_ulid.orm" raises a Pydantic ValidationError in Ninja 1.7.1. Its first error includes ImproperlyConfigured: Requested setting NINJA_PAGINATION_CLASS, but settings are not configured.
If DJANGO_SETTINGS_MODULE is set but you import your app's models before django.setup(), Django raises django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
In a Django project, put the ORM imports in the API module that your URL configuration loads. In a standalone script, initialize Django before importing helpers or models. Use your project's settings module in place of config.settings.
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
from django_ninja_ulid.orm import create_ulid_response_schema
from catalog.models import Item
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. Nested responses and other ULID field libraries are outside its scope. For create and PATCH endpoints, see Request schemas.
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. - Response schemas generated by
create_ulid_response_schemaadvertise uppercase-only ULIDs, including each item in a list of related IDs. Hand-written schemas usingApiULIDallow lowercase in both request and response patterns because Ninja 1.7.1 and 1.8.0 use one OpenAPI component for a class shared by a request and a response. Serialized ULIDs are 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 (English and Japanese)
- Versioning policy (Japanese)
- Development and bug reports (Japanese)
- Report an issue
License
Metadata
Release files for django-ninja-ulid 0.2.0
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.2.0.tar.gz | 115.1 kB | With provenance | Details for django_ninja_ulid-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_ninja_ulid-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for django_ninja_ulid-0.2.0-py3-none-any.whl |
Total release size: 126.1 kB
Release files / django_ninja_ulid-0.2.0.tar.gz
| Download URL | django_ninja_ulid-0.2.0.tar.gz |
|---|---|
| Size | 115.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ad5cd34c23cf4d6012d99a63d7ec81bbf3b4bc52ec546f4ef747f918f70b4aa4
|
|
BLAKE2b-256 checksum How to use checksums |
a4f1b66f1da93e9b481b64fd98a8a20377b888e13c31ff9ce139f14062b38b2b
|
| 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.2.0-py3-none-any.whl
| Download URL | django_ninja_ulid-0.2.0-py3-none-any.whl |
|---|---|
| Size | 11.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5a420b13ec03f1b7d157f3c70da05fd4bc0ed71842e26eb5a2d74533787c6784
|
|
BLAKE2b-256 checksum How to use checksums |
16f0897562c706b3710e8150a98cee6feb20a0eab50474394318c07cdef50b08
|
| 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.2.0
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.2.0.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.