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
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.core.urlresolvers import reverse
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
urls.py
urlpatterns = [
url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
]
Actual output
[
{
"id":1,
"title":"",
"code":"foo = \"bar\"\n",
"linenos":false,
"language":"python",
"style":"friendly"
}
]
Desired output
[
{
"id":1,
"url":"http://192.168.28.131:8000/snippets/1/",
"title":"",
"code":"foo = \"bar\"\n",
"linenos":false,
"language":"python",
"style":"friendly"
},
]
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'),
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With