[Django]-How to use ListSerializer with a ModelSerializer?

0๐Ÿ‘

โœ…

Had to handle this error by updating to_representation method on the PrimaryKeyRelatedField class

class NodePrimaryKeyField(serializers.PrimaryKeyRelatedField):
    """
    Custom DRF serializer field for proper handling of
    Node Foreign Key by ListSerializer on validation error
    """
    def to_representation(self, value):
        """
        Return pk value of serialized Node object
        if available else return given ID value
        """
        if self.pk_field is not None:
            return self.pk_field.to_representation(value.pk)
        return getattr(value, 'pk', value)
๐Ÿ‘คbbmhmmad

0๐Ÿ‘

The serializer.data property is only valid if you have a saved an instance to the serializer.
Either call serializer.save() or use serializer.validated_data to access data prior to saving.

Checkout this link for further information.

๐Ÿ‘คRene B.

Leave a comment