

lookup_url_kwarg: Specifies the name of the URL parameter that should be used to look up the related resource.lookup_field: Specifies the name of the field on the related model that should be used to generate the URL for the related resource.

This is required for HyperlinkedRelatedField and HyperlinkedIdentityField. view_name: Specifies the name of the view that should be used to generate the URL for the related resource.

In addition to the options discussed above, there are a few other ways to customize URL fields in serializers. In this example, the url field is defined as a URLField, which allows us to include a URL to an external resource.
#Django rest framework serializer fields how to#
Here's an example of how to use HyperlinkedRelatedField to link to a related author resource:įrom rest_framework import serializers class ExternalResourceSerializer(serializers.Serializer): name = serializers.CharField() url = serializers.URLField() It creates a hyperlink to a related resource, and can be used with any model that has a corresponding URL endpoint. The HyperlinkedRelatedField class is the most commonly used URL field in Django Rest Framework. Let's take a closer look at some of the most common options: HyperlinkedRelatedField When defining URL fields in serializers, there are a few different options we can use to customize their behavior. The view_name argument specifies the name of the view that should be used to generate the URL, and the read_only argument tells Django Rest Framework that this field should be read-only and should not be included when the serializer is used for deserialization. In this example, the author field is defined as a HyperlinkedRelatedField, which creates a hyperlink to the related author resource. Class BookSerializer(serializers.ModelSerializer):Īuthor = serializers.HyperlinkedRelatedField(įields = ('id', 'title', 'author', 'published_date')
