Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customize enum choices in serializer #120

Open
MehdiDRISSIB opened this issue Feb 15, 2021 · 2 comments
Open

Customize enum choices in serializer #120

MehdiDRISSIB opened this issue Feb 15, 2021 · 2 comments

Comments

@MehdiDRISSIB
Copy link

MehdiDRISSIB commented Feb 15, 2021

Hello

Is that possible to restrict choices of enum class in serializer ?

This is my enum class:

class TransferType(Enum):
    Paypal = "PP"
    WesternUnion = "WU"
    Wallet = "WT"

    class Labels:
        Paypal = _('Paypal')
        WesternUnion = _('Western Union')
        Wallet = _('Wallet')

My serializer:

class TransferSerializer(EnumSupportSerializerMixin, serializers.ModelSerializer):
    wallet = serializers.SerializerMethodField(source='get_wallet')
    transfer_type = EnumField(enum=[TransferType.Paypal, TransferType.WesternUnion ])
    .......

I got this error when I post data:

isinstance() arg 2 must be a type or tuple of types

Exception Value: | isinstance() arg 2 must be a type or tuple of types
Exception Location: C:\Users\mehdi\PycharmProjects\venv\lib\site-packages\enumfields\drf\fields.py, line 35, in to_internal_value

Thank you

@akx
Copy link
Contributor

akx commented Feb 15, 2021

You can't pass in a list where an enum is expected. Better just add a validator function.

def validate_transfer_type(self, value: TransferType):
    if value == TransferType.Wallet:
        raise serializers.ValidationError("Wallet transfers not supported")
    return value

@MehdiDRISSIB
Copy link
Author

MehdiDRISSIB commented Feb 16, 2021

Thanks a lot for your quick answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants