drf_serpy.Serializer
Serializer Objects
class Serializer(SerializerBase, metaclass=SerializerMeta)
Serializer` is used as a base for custom serializers.
The Serializer class is also a subclass of Field, and can
be used as a Field to create nested schemas. A serializer is
defined by subclassing Serializer and adding each Field
as a class variable:
Example:
class FooSerializer(Serializer):
foo = Field()
bar = Field()
foo = Foo(foo='hello', bar=5)
FooSerializer(foo).data
# {'foo': 'hello', 'bar': 5}
Arguments:
instance: The object or objects to serialize.many(bool): Ifinstanceis a collection of objects, setmanytoTrueto serialize to a list.context(dict): Currently unused parameter for compatability with Django REST Framework serializers. you can manually pass the context in and use it on the functions like as a runtime attribute
default_getter
The default getter used if :meth:Field.as_getter returns None.
data
@property
def data() -> Dict
Get the serialized data from the Serializer.
The data will be cached for future accesses.
to_schema
@classmethod
def to_schema(cls: SerializerMeta, many: bool = False, *args, **kwargs) -> openapi.Response:
Convert Serializer to openapi.Schema
DictSerializer Objects
class DictSerializer(Serializer)
DictSerializer serializes python dicts instead of objects.
Instead of the serializer's fields fetching data using
operator.attrgetter, DictSerializer uses
operator.itemgetter.
Example:
class FooSerializer(DictSerializer):
foo = IntField()
bar = FloatField()
foo = {'foo': '5', 'bar': '2.2'}
FooSerializer(foo).data
# {'foo': 5, 'bar': 2.2}