Skip to content
Advertisement

How to add an url field to a serializer with Django Rest Framework

I am following the tutorial on Django Rest Framework – Tutorial 3 Class based views.

How to add an url field (pointing to the current snippet) to a serializer?

serializers.py

JavaScript

urls.py

JavaScript

Actual output

JavaScript

Desired output

JavaScript

Advertisement

Answer

You have to use HyperlinkedModelSerializer serializer and HyperlinkedIdentityField field

From Django Rest Framework documentation

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.

E.g (with your case) :

JavaScript

Of course, view_name value must match the name of an url declared in urls.py (or not elsewhere) used to get all information about a snippet.

E.g :

JavaScript
Advertisement