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?

+3


source to share


5 answers


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

      

+4


source


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)

      

+3


source


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/

+2


source


According to this issue, you can simply add 'url' to the list of fields.

+1


source


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')

      

+1


source







All Articles