Post to HyperlinkedModelSerializer

Hi there,

I have a DRF project where I’m trying to build an api using a HyperlinkedModelSerializer (in combination with a ViewSet).

This is works fine for GET requests, but for POST requests, I can see the HyperlinkedRelatedField requires the full url of the related field. I guess this is as expected, but I was hoping I could override this so a user of the api could just supply a value for the lookup_field rather than the full url.

I’m a bit stuck on where to override this behaviour and was hoping someone could point me in the right direction. Would I create a “duplicate” ModelSerializer and override the POST in the viewset referencing the ModelSerializer as opposed to the HyperlinkedModelSerializer, or is this something I can simply override in HyperlinkedModelSerializer itself?

Thanks in advance!

Not sure if this is the optimal approach, but I’ve overridden get_serializer_class on the ViewSet to use a ModelSerializer for POST/PUT methods.


I think you’ve arrived at what be the simplest way to meet your requirements. Serializers by default serialize their data the same way in both directions.

The lookup can allow you to get an object with, for example, a slug instead of its ID, but required data would still require the full URL.

I recently saw a good blog POST, one of three, on serializing data differently depending on whether it was incoming or outgoing.

Cool thanks Conor, I’ll take a look :+1: