How to add an url field to a serializer with Django Rest Framework
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 aHyperlinkedIdentityField
serializer field, and any relationships on the model will be represented using aHyperlinkedRelatedField
serializer field.
E.g (with your case) :
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='snippet-detail', read_only=True)
class Meta:
model = Snippet
fields = ('id', 'url', 'title', 'code', 'linenos', 'language', 'style')
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 :
# urls.py
urlpatterns = [
url(r'^snippets/(?P<pk>[0-9]+)$', views.SnippetDetail.as_view(), name='snippet-detail'),
]