The Python Oracle

Conditional field requirement with DjangoRestFramework serializer

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 Question
00:49 Accepted answer (Score 10)
01:18 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()