Conditional field requirement with DjangoRestFramework serializer
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Conditional Field Requirement With Djangorestframework Serializer
00:40 Accepted Answer Score 10
01:06 Thank you
--
Full question
https://stackoverflow.com/questions/3572...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #serialization #djangorestframework
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Conditional Field Requirement With Djangorestframework Serializer
00:40 Accepted Answer Score 10
01:06 Thank you
--
Full question
https://stackoverflow.com/questions/3572...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #serialization #djangorestframework
#avk47
ACCEPTED ANSWER
Score 10
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()