Just getting into Django Rest Framework.
I have a simple example running where a model is being presented through the REST API. There are no Related fields in the model, just a bunch of strings.
What is the easiest way to present the get_absolute_url()
value of that model into the JSON output?
I'm using serializers.HyperlinkedModelSerializer
in preparation for moving into more complicated models that do have related fields.
Approach-1 Using a SerializerMethodField
:
You can use a SerializerMethodField
in your serializer to add the get_absolute_url()
value to the serialized representation of the object.
As per the SerializerMethodField
docs:
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
We will define a method get_my_abslute_url()
for the my_absolute_url
field in our serializer which will add the absolute url of the object to the serialized representation.
class MyModelSerializer(serializers.ModelSerializer):
my_absolute_url = serializers.SerializerMethodField() # define a SerializerMethodField
def get_my_absolute_url(self, obj):
return obj.get_absolute_url() # return the absolute url of the object
Approach-2 Using URLField
with source
argument:
You can also use a URLField
and pass the method get_absolute_url
to it. This will call the method get_absolute_url
and return that value in the serialized representation.
From DRF docs on source
argument:
The name of the attribute that will be used to populate the field. May be a method that only takes a
self argument
, such asURLField('get_absolute_url')
, or may use dotted notation to traverse attributes, such asEmailField(source='user.email')
.
class MyModelSerializer(serializers.ModelSerializer):
my_absolute_url = serializers.URLField(source='get_absolute_url', read_only=True)
I would suggest using the 2nd approach as DRF has explicitly used this in its docs.
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