Skip to content

Commit

Permalink
Serialize missing field values for none
Browse files Browse the repository at this point in the history
  • Loading branch information
stevelacey committed Mar 7, 2023
1 parent 02da6a3 commit 5c75d48
Showing 1 changed file with 35 additions and 11 deletions.
46 changes: 35 additions & 11 deletions worf/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,25 @@
from django.db.models import Manager


class File(fields.Field):
class SerializeMissing:
def __init__(self, *args, **kwargs):
if "dump_default" not in kwargs:
kwargs["dump_default"] = [] if kwargs.get("many") else None
return super().__init__(*args, **kwargs)


class SerializeQuerysets:
def _serialize(self, nested_obj, attr, obj, **kwargs):
if isinstance(nested_obj, Manager):
nested_obj = nested_obj.all()
return super()._serialize(nested_obj, attr, obj, **kwargs)


class Field(SerializeMissing, fields.Field):
pass


class File(Field):
_CHECK_ATTRIBUTE = False

def __init__(self, serialize=None, deserialize=None, **kwargs):
Expand Down Expand Up @@ -34,15 +52,21 @@ def _call_or_raise(self, func, value, attr):
return func(value)


class Nested(fields.Nested):
def _serialize(self, nested_obj, attr, obj, **kwargs):
if isinstance(nested_obj, Manager):
nested_obj = nested_obj.all()
return super()._serialize(nested_obj, attr, obj, **kwargs)
class Nested(SerializeQuerysets, fields.Nested):
pass


class Pluck(fields.Pluck):
def _serialize(self, nested_obj, attr, obj, **kwargs):
if isinstance(nested_obj, Manager):
nested_obj = nested_obj.all()
return super()._serialize(nested_obj, attr, obj, **kwargs)
class Pluck(SerializeQuerysets, fields.Pluck):
pass


for field in map(fields.__dict__.get, fields.__all__):
if fields.Field not in field.__bases__ or SerializeMissing in field.__bases__:
continue
field.__bases__ = (SerializeMissing, *field.__bases__)


__all__ = [
*fields.__all__,
"File",
]

0 comments on commit 5c75d48

Please sign in to comment.