DjangoRestFramework - exclude empty 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 a way to tell DRF that if the value of the field is null (since the country field is optional and sometimes not provided), then 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 also write, if provided).

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

+6
source share
2 answers

As with DRF 3.2.4, while you add

 blank=True 

in the model field, for example:

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

then DRF will treat the field as optional during serialization and deserialization (note that if the model field does not have null = True, then Django will cause an error if you try to save the object in the database without providing the field).

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

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

So something like this (note that I have not fully tested the code below, but it should be something like these lines):

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

This thread may be useful:

fooobar.com/questions/329063 / ...

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

I would put this in a comment, but so far I have not got enough points :(

+2
source

All Articles