Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove null fields from Django Rest Framework response

Tags:

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"     } } 
like image 563
Dev Rishi Khare Avatar asked Nov 19 '14 11:11

Dev Rishi Khare


2 Answers

I found this solution to be the simplest.

from collections import OrderedDict from rest_framework import serializers  class NonNullModelSerializer(serializers.ModelSerializer):     def to_representation(self, instance):         result = super(NonNullModelSerializer, self).to_representation(instance)         return OrderedDict([(key, result[key]) for key in result if result[key] is not None]) 
like image 144
Simon Avatar answered Oct 14 '22 07:10

Simon


I faced a similar problem and solved it as follows:

from operator import itemgetter   class MetaTagsSerializer(serializers.ModelSerializer):     class Meta:         model = MetaTags      def to_representation(self, instance):         ret = super().to_representation(instance)         # Here we filter the null values and creates a new dictionary         # We use OrderedDict like in original method         ret = OrderedDict(filter(itemgetter(1), ret.items()))         return ret 

Or if you want to filter only empty fields you can replace the itemgetter(1) by the following:

lambda x: x[1] is not None 
like image 40
asduj Avatar answered Oct 14 '22 07:10

asduj