liveBook · Manning

Slug

As explained in Django in Action

A slug is a short, URL-compatible textual identifier or descriptive name for a resource.

A slug is a short, URL-compatible name for a resource. Compare `/song/43/` with `/song/paint-it-black/`: the second URL is easier for people to read and gives search engines a clue about its destination. section 11.2.2

A practical pattern combines readable text with a numeric identifier, such as `/song/paint-it-black-43/`. The slug explains the resource, while the ID makes database lookup straightforward; the slug does not necessarily need to be stored. section 11.2.2

Django supports slugs in two useful ways:

  • Use SlugField when storing a slug on a model; it adds validation for identifiers made from letters, numbers, and dashes. section 4.8.2
  • Generate a slug for an API response with Django's slugify function, then append the object's ID to preserve a reliable lookup value. section 11.2.2

Adding a slug to a Venue API response

A Django Ninja serializer can declare `slug: str`, generate it with `slugify(obj.name) + "-" + str(obj.id)`, and return values such as `"cbgb-1"`. The endpoint still retrieves the Venue with `id=venue_id`; the slug improves the representation without changing the lookup path.

How Django in Action covers it

How deep it goes
Explains URL naming, stored-field validation, and serializer generation, but stops short of designing complete slug-based routes.
Examples
Uses song URLs, a Venue serializer, the generated `cbgb-1` value, and an ID-based venue endpoint.
What it assumes
Builds from Django model fields and Python type hints, while introducing slug validation and generation through concrete API code.
What you can do after
Apply it via Django Ninja by generating readable serializer fields while continuing to fetch objects through numeric IDs.
How it connects
Connects slugs with URLs, database identifiers, Django models, Django Ninja serializers, and API endpoints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.