I have these nested serializers in Django Rest Framework 2:
class BookingSerializer(Serializer):
reservation_history_id = serializers.IntegerField()
credit_card = 'api.v1.serializer.AddCreditCardSerializer()'
save_credit_card = serializers.BooleanField()
promo_code = serializers.BooleanField(required=False)
# validation stuff here ...
class AddCreditCardSerializer(ModelSerializer):
""" Credit card model serializer """
expiration_date = serializers.CharField()
card_number = serializers.CharField()
security_code = serializers.IntegerField()
# validation stuff here ...
In my ApiView BookingApiView
, I'm calling a BookingSerializer
.
I would like to make credit card fields mandatory or not, according to a backend method that returns True or False.
How can I do this? Thanks.
You can modify the fields in the __init__
method of BookingSerializer
.
After initialization the fields are accessible in self.fields
class BookingSerializer(Serializer):
reservation_history_id = serializers.IntegerField()
credit_card = 'api.v1.serializer.AddCreditCardSerializer()'
save_credit_card = serializers.BooleanField()
promo_code = serializers.BooleanField(required=False)
def __init__(self, *args, **kwargs):
# initialize fields
super(BookingSerializer, self).__init__(*args, **kwargs)
# now modify the creditcard field
self.fields['credit_card'].required = yourBackendMethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With