我在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 ...
在我的ApiView BookingApiView
中,我正在呼叫BookingSerializer
。
根据返回True或False的后端方法,我想强制或不强制信用卡字段。
我怎样才能做到这一点?感谢。
答案 0 :(得分:7)
您可以修改__init__
BookingSerializer
方法中的字段。
初始化后,可以在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()