Approach-1 Using SerializerMethodField :
You can use SerializerMethodField in your serializer to add the get_absolute_url() value to the serialized representation of the object.
According to SerializerMethodField docs:
This field is read only. It gets its value by invoking a method on to the serializer class to which it is attached. It can be used to add any sorting of data to the serialized representation of your object.
We will define the get_my_abslute_url() method for the my_absolute_url field in our serializer, which will add the absolute URL of the object to the serialized view.
class MyModelSerializer(serializers.ModelSerializer): my_absolute_url = serializers.SerializerMethodField()
Approach-2 Using URLField with argument source :
You can also use the URLField and pass the get_absolute_url method to get_absolute_url . This will call the get_absolute_url method and return that value to the serialized view.
From DRF docs to source argument:
The name of the attribute that will be used to populate the field. May be a method that accepts only a self argument , such as URLField('get_absolute_url') , or can use dotted notation to traverse attributes like EmailField(source='user.email') .
class MyModelSerializer(serializers.ModelSerializer): my_absolute_url = serializers.URLField(source='get_absolute_url', read_only=True)
I would suggest using the second approach , since DRF explicitly used this in its docs.
source share