I have a model with a nullable boolean field that I'd like to have serialized in a way that converts null
in the output to false
.
My model:
class UserPreferences(models.Model):
receive_push_notifications = models.BooleanField(
null=True, blank=True,
help_text=("Receive push notifications))
I'm trying to do it with a custom field like so:
class StrictlyBooleanField(serializers.Field):
def to_representation(self, value):
# Force None to False
return bool(value)
def to_internal_value(self, data):
return bool(data)
class UserPreferencesSerializer(serializers.ModelSerializer):
class Meta(object):
model = UserPreferences
fields = ('receive_push_notifications',)
receive_push_notifications = StrictlyBooleanField()
but this isn't working, I'm still seeing null
in my API responses.
I think I must be missing something simple in wiring it up because I don't even get an error if I replace my to_representation
with:
def to_representation(self, value):
raise
DRF doesn't seem to be calling my method at all... What am I missing here?