Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DjangoRestFramework - Omit null fields when serializing objects

This is my Model:

class Post(models.Model):
    user = models.ForeignKey(User)
    post = models.CharField(max_length=400)
    country = models.ForeignKey(Country, blank=True, null=True)

and this is my serializer:

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('user', 'post', 'country',)

    def create(self, validated_data):
        post = Post(
                user =  User.objects.get(username='MyUser'),
                post = validated_data['post'],
        )

        if validated_data.get('country', None):
            post.country = validated_data['country']

        return post

Is there any way for me to tell DRF that if the value of the field is null (because the 'country' field is optional and sometimes not provided) then to skip it and just serialize the other data? Or at least serialize it with a value of None?

I don't think I can use SerializerMethodField (http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield) because the 'country' field is not a read-only field (I write too it too, if it is provided).

I basically want to omit the field (or at least make the value None) when serializing an object If the field is null.

like image 262
SilentDev Avatar asked Oct 07 '15 03:10

SilentDev


People also ask

How to ignore null or empty fields when serializing a Java class?

In this quick tutorial, I show you how to set up Jackson to ignore null or empty fields when serializing a Java class. Jackson provides Include.NON_NULL to ignore fields with Null values and Include.NON_EMPTY to ignore fields with Empty values. By default, Jackson does not ignore Null and Empty fields while writing JSON.

What is a serializer field in Django?

— Django documentation Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.

What is the default kwarg for booleanfield in Django?

Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option.

Is there a way to ignore null values when serializing maps?

There are, however, more advanced use cases, such as ignoring null values when serializing a Map. The implementation of all of these examples and code snippets can be found in the Github project. Comments are closed on this article!


2 Answers

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',)
like image 116
SilentDev Avatar answered Oct 22 '22 23:10

SilentDev


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

like image 25
prawg Avatar answered Oct 22 '22 23:10

prawg