Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent `self` url in django-rest-framework

I want to add a link to a single resource representation which is an URL to itself, self. Like (taken from 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 should this be done?

like image 521
Sam R. Avatar asked Dec 10 '22 23:12

Sam R.


2 Answers

If you inherit serializers.HyperlinkedModelSerializer all you need to do is pass a url field to fields. See the docs here:

http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

like image 176
Lorenzo Peña Avatar answered Jan 29 '23 10:01

Lorenzo Peña


Alright, 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)
like image 36
Sam R. Avatar answered Jan 29 '23 10:01

Sam R.