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.
source share