DjangoRestFramework - Omit null fields when serializing objects

This thread might be useful:

https://stackoverflow.com/a/28870066/4698253

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 :(


As of DRF 3.2.4, so long as you add

blank=True

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',)