Including get_absolute_url value in JSON output

Just hitting the Django Rest Framework.

I have a simple example in which a model is represented through a REST API. There are no related fields in the model, just a few lines.

What is the easiest way to represent the get_absolute_url() value of this model in JSON output?

I use serializers.HyperlinkedModelSerializer to prepare for more complex models that have related fields.

+5
source share
1 answer

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() # 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 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.

+6
source

Source: https://habr.com/ru/post/1233242/


All Articles