Skip to content

Commit

Permalink
Add custom NullBooleanField to convert null values to False
Browse files Browse the repository at this point in the history
  • Loading branch information
psiemens committed Oct 31, 2018
1 parent d9a0842 commit 50a8548
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
17 changes: 15 additions & 2 deletions dispatch/api/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,28 @@
from rest_framework.exceptions import ValidationError

class JSONField(Field):

def to_internal_value(self, data):
return data

def to_representation(self, value):
return value

class PrimaryKeyField(Field):
class NullBooleanField(Field):
"""Forces a Django NullBooleanField to always return False for null values."""

def get_attribute(self, instance):
"""Overrides the default get_attribute method to convert None values to False."""

attr = super(NullBooleanField, self).get_attribute(instance)
return True if attr else False

def to_internal_value(self, data):
return True if data else None

def to_representation(self, value):
return True if value else False

class PrimaryKeyField(Field):
def __init__(self, serializer, *args, **kwargs):
super(PrimaryKeyField, self).__init__(*args, **kwargs)

Expand Down
6 changes: 5 additions & 1 deletion dispatch/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from dispatch.api.validators import (
FilenameValidator, ImageGalleryValidator, PasswordValidator,
SlugValidator, AuthorValidator, TemplateValidator)
from dispatch.api.fields import JSONField, PrimaryKeyField, ForeignKeyField
from dispatch.api.fields import JSONField, NullBooleanField, PrimaryKeyField, ForeignKeyField

class PersonSerializer(DispatchModelSerializer):
"""Serializes the Person model."""
Expand Down Expand Up @@ -608,6 +608,8 @@ class ArticleSerializer(DispatchModelSerializer, DispatchPublishableSerializer):
id = serializers.ReadOnlyField(source='parent_id')
slug = serializers.SlugField(validators=[SlugValidator()])

is_published = NullBooleanField(read_only=True)

section = SectionSerializer(read_only=True)
section_id = serializers.IntegerField(write_only=True)

Expand Down Expand Up @@ -770,6 +772,8 @@ class PageSerializer(DispatchModelSerializer, DispatchPublishableSerializer):
id = serializers.ReadOnlyField(source='parent_id')
slug = serializers.SlugField(validators=[SlugValidator()])

is_published = NullBooleanField(read_only=True)

featured_image = ImageAttachmentSerializer(required=False, allow_null=True)
featured_video = VideoAttachmentSerializer(required=False, allow_null=True)

Expand Down

0 comments on commit 50a8548

Please sign in to comment.