Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework url in json

I noticed in the example REST framework site here http://restframework.herokuapp.com/snippets/ that there is a field called 'url' for each user which conveniently links to the user details page. Where on the Django REST documentation is their an example on how to achieve this, or can someone provide me with an example?

like image 446
jason Avatar asked Jan 30 '26 19:01

jason


2 Answers

Use serializers.HyperlinkedModelSerializer and add 'url this should add the details part in.

Link: serializers.HyperlinkedModelSerializer

UPDATE:

You can add the ID in with the HyperlinkedModelSerializer just add....

  id = serializers.Field()

Done :)

like image 54
Glyn Jackson Avatar answered Feb 01 '26 17:02

Glyn Jackson


There's an entire page of the tutorial dedicated to this topic: http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html

Check the section marked "Hyperlinking our API". It shows the code that defines the JSON you see in that page:

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.Field(source='owner.username')
    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

    class Meta:
        model = models.Snippet
        fields = ('url', 'highlight', 'owner',
                  'title', 'code', 'linenos', 'language', 'style')
like image 34
Mariano Avatar answered Feb 01 '26 19:02

Mariano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!