使用DjangoRestFramework序列化程序的条件字段要求

时间:2016-03-01 11:19:28

标签: python django serialization django-rest-framework

我在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的后端方法,我想强制或不强制信用卡字段。 我怎样才能做到这一点?感谢。

1 个答案:

答案 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()