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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With