Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework HyperLinkedRelatedField: allow id instead of url for POSTS requests

I would like to allow a HyperLinkRelatedField to accept just an id instead of requiring a hyperlink to create a new instance of an object, but for get requests I would like to return the hyperlink not just an id but it appears to be either one or the other. Is this possible?

class Blog(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Blog
        fields = ('url', 'id')

class Comment(serializers.HyperlinkedModelSerializer):
    blog = serializers.HyperlinkedRelatedField(view_name='blog-detail', queryset=Blog.objects.all())
    class Meta:
        model = Comment
        fields = ('url', 'text', 'blog')


GET Request for Comment returns (This is perfect):

{'url': 'mysite.fake/comments/1', 'text': 'test text', 'blog': 'mysite.fake/blog/1'}


POST Request requires:

{'text': 'test text', 'blog': 'mysite.fake/blog/1'}

I want to also be able to pass:

{'text': 'test text', 'blog': '1'}
like image 470
jshcrm Avatar asked Aug 30 '17 16:08

jshcrm


1 Answers

It is possible but not out of the box.

You should use a ModelSerializer and define your own relational field. Start with a PrimaryKeyRelatedField and override the to_representation so it returns an url instead of an id.

like image 99
Linovia Avatar answered Sep 20 '22 00:09

Linovia