I have developed an API using django-rest-framework. I am using ModelSerializer to return data of a model.
models.py
class MetaTags(models.Model):
title = models.CharField(_('Title'), max_length=255, blank=True, null=True)
name = models.CharField(_('Name'), max_length=255, blank=True, null=True)
serializer.py
class MetaTagsSerializer(serializers.ModelSerializer):
class Meta:
model = MetaTags
response
{
"meta": {
"title": null,
"name": "XYZ"
}
}
Ideally in an API response any value which is not present should not be sent in the response.
When the title
is null
I want the response to be:
{
"meta": {
"name": "XYZ"
}
}
The answer from CubeRZ didn't work for me, using DRF 3.0.5. I think the method to_native has been removed and is now replaced by to_representation, defined in Serializer instead of BaseSerializer.
I used the class below with DRF 3.0.5, which is a copy of the method from Serializer with a slight modification.
EDIT incorporated code from comments
I faced a similar problem and solved it as follows:
Or if you want to filter only empty fields you can replace the lambda function by the following:
You could try overriding the to_native function:
I basically copied the base to_native function from
serializers.BaseSerializer
and added a check for the value.UPDATE: As for DRF 3.0,
to_native()
was renamed toto_representation()
and its implementation was changed a little. Here's the code for DRF 3.0 which ignores null and empty string values:I found this solution to be the simplest.