How to represent `self` url in django-rest-framework
I want to add a link to one of the resource, which is a URL-address for yourself self
. Like (taken from the documentation):
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Album
fields = ('album_name', 'artist', 'track_listing')
{
'album_name': 'The Eraser',
'artist': 'Thom Yorke',
'self': 'http://www.example.com/api/album/2/',
}
How to do it?
source to share
here is my solution,
in your view methods create a serilizer object like this:
album = AlbumSerializer(data=data, {"request":request})
in your serilizer class override method to_representation
(you can read about this method DRF docs
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
def to_representation(self, obj):
data = super().to_representation(obj)
request = self.context["request"]
return data
source to share
Ok this solved my problem, but if you have a better solution please post an answer:
from django.urls import reverse
from rest_framework import serializers
self_url = serializers.SerializerMethodField('get_self')
def get_self(self, obj):
request = self.context['request']
return reverse('album-detail', kwargs={'id': obj.id}, request=request)
source to share
If you are inheriting serializers.HyperlinkedModelSerializer
, all you have to do is pass the field url
to fields
. See docs here:
http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/
source to share
Here's a little more context than what you've gotten in other answers so far. The key is the argument context
passed to the serializer constructor and fields 'url'
.
http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/
In your view:
class AlbumViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Album.objects.all()
serializer = AlbumSerializer(queryset, many=True,
context={'request': request})
return Response(serializer.data)
In the serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Album
fields = ('album_name', 'artist', 'track_listing', 'url')
source to share