Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional field requirement with DjangoRestFramework serializer

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.

like image 207
David D. Avatar asked Mar 01 '16 11:03

David D.


1 Answers

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()
like image 98
ilse2005 Avatar answered Sep 18 '22 12:09

ilse2005