Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Serializers

Relational Fields: Keys, Slugs and Hyperlinks

Represent relationships in DRF with PrimaryKeyRelatedField, SlugRelatedField, StringRelatedField and HyperlinkedRelatedField, including many-to-many and write behavior.

Not every relationship needs a full nested object. Sometimes a client only needs an id, a readable label or a URL it can follow. DRF's relational fields cover those cases. They represent a related object (or a list of them) in a compact form and, when writable, translate that form back into a model instance on input.

This lesson compares the five relational fields side by side, shows what ModelSerializer picks by default, and explains the queryset rule for writable relations.

The five representations

Take a Book that belongs to an Author and has many Tags. Here is how the same book can look:

Field Output for author Input accepted
PrimaryKeyRelatedField (default) 1 1
StringRelatedField "Ada Lovelace" (the model's __str__) read-only
SlugRelatedField(slug_field="name") "Ada Lovelace" (any unique field) the slug value
HyperlinkedRelatedField "/authors/1/" (a URL) the URL
nested serializer {"id": 1, "name": "..."} covered in Nested Serializers
Python One relation, four representations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ModelSerializer picks PrimaryKeyRelatedField for relations unless you say otherwise, which is why the first line shows bare ids. Each variant is a trade-off:

  • Primary keys are compact and stable, but clients need another request to see names.
  • StringRelatedField is read-only and uses __str__. It is a quick way to show labels, but you cannot write through it, and it triggers one query per object unless you prefetch.
  • Slugs make writes human-friendly ("tags": ["fiction", "math"]), as long as the chosen field is unique.
  • Hyperlinks give clients URLs to follow instead of ids to assemble into URLs, the style used by "hypermedia" APIs. They need a request in the serializer context (views and viewsets add it for you) and a named URL pattern.

Writing through relational fields

A writable relational field needs a queryset. DRF uses it to look up the object that the incoming key or slug refers to, and the same queryset is the whitelist of what a client may link to.

Python Writable relations and their errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the errors: a slug that matches nothing is rejected with "Object with name=Nobody does not exist", an author excluded from the queryset is rejected the same way, and one bad id in a list fails the whole list. The many=True variant expects a list, and sending a string gives a clear type error.

Restrict the queryset to what the current user may link to. Overriding get_queryset() on a custom related field (or using context["request"].user) prevents users from attaching their records to other users' objects.

Many-to-many and reverse relations

  • A many-to-many field (tags) is a list on output and on input. DRF assigns it with .set() after the instance is created, so it works with plain ModelSerializer code.
  • A reverse relation (author.books) is not included by default. Add its related_name to fields to show a list of ids, or declare PrimaryKeyRelatedField(many=True, read_only=True) explicitly.
  • A many-to-many relation with a through model that has extra columns is read-only through relational fields. Write those with a nested serializer and a custom create().

HyperlinkedModelSerializer

serializers.HyperlinkedModelSerializer is ModelSerializer with two changes: relations become hyperlinks and the output has a url field for the object itself instead of an id. It expects named routes like author-detail and book-detail, which a router creates for you (see Routers).

Python
class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ["url", "title", "author", "tags"]

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which relational field does ModelSerializer use for a foreign key by default?

    Relations are shown as primary keys unless you declare another field.
  2. 2. Why does a writable relational field need a queryset?

    DRF searches that queryset for the key or slug; anything outside it is rejected.
  3. 3. Which field is read-only and uses the model's str?

    StringRelatedField only produces output, based on str(obj).
  4. 4. What must be available for HyperlinkedRelatedField to build URLs?

    It calls reverse() with the view name and needs the request to build absolute URLs.

Summary

  • Relational fields give compact representations of related objects: keys, strings, slugs or links.
  • ModelSerializer defaults to primary keys.
  • Writable relations need a queryset, which also limits what clients may link to.
  • Use prefetch_related to avoid per-object queries with string and nested fields.
  • Hyperlinks need a request in the context and named URL patterns.

Next: Class-Based Views with APIView