Including the get_absolute_url value in JSON output
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.