[Fixed]-DjangoRestFramework – Omit null fields when serializing objects


As of DRF 3.2.4, so long as you add


to the models field like so:

class Post(models.Model):
    country = models.ForeignKey(Country, blank=True)

then DRF will treat the field as optional when serializing and deserializing it (Note though that if there is no null=True on the model field, then Django will raise an error if you try to save an object to the database without providing the field).

See the answer here for more information: DjangoRestFramework – correct way to add "required = false" to a ModelSerializer field?

If you are using pre-DRF 3.2.4, then you can override the field in the serializer and add required=False to it. See the documentation here for more information on specifying or overriding fields explicitily: http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly

So something like this (Note that I did not fully test the code below but it should be something along these lines):

class PostSerializer(serializers.ModelSerializer):
    country = serializers.PrimaryKeyRelatedField(required=False)
    class Meta:
        model = Post
        fields = ('user', 'post', 'country',)


This thread might be useful:


It basically says that you can override the to_representation() function with a slight modification.

I would have put this in the comments but I don’t have enough points yet 🙁



Use allow_null=True:

allow_null – If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.


class PostSerializer(serializers.ModelSerializer):
    tracks = serializers.PrimaryKeyRelatedField(allow_null=True)

    class Meta:
        model = Post

Leave a comment