Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

—Someone on Stack Overflow

Sometimes data exposed via the API has a different shape, depending on the value of a field that’s common to all possible shapes.

This module adds support for polymorphic serializing and deserializing of this data.

You use it by defining a base serializer for the shared fields (at least one, used as discriminator field), and map the values of the discriminator to the additional fields that need to be displayed.

A field inspector is included to output is correctly into an OAS 2.0 schema.

Public API

Implement polymorphism at the API level.

Add support to DRF serializers for polymorphic resources. Polymorphic resources take a certain shape depending on the value of a field, called the discriminator. The model itself does not need to be made polymorphic, allowing database queries to remain performant.


>>> from vng_api_common.polymorphism import Discriminator, PolymorphicSerializer
>>> class AutorisatieBaseSerializer(PolymorphicSerializer):
...     discriminator = Discriminator(
...         discriminator_field='type',
...         mapping={
...             'value1': (
...                 'field_for_value1',
...             ),
...             'value2': (
...                 'field_for_value2',
...             ),
...         }
...     )
...     class Meta:
...         model = SomeModel
...         fields = (
...             'type',
...             'common_field',
...         )

The serializer output will then either contain field_for_value2 or field_for_value2, depending on the value of the field type.

class vng_api_common.polymorphism.PolymorphicSerializer(*args, **kwargs)

Dict of native values <- Dict of primitive datatypes.


Object instance -> Dict of primitive datatypes.