gpt4 book ai didi

python - DjangoRestFramework 序列化程序的条件字段要求

转载 作者:太空狗 更新时间:2023-10-30 00:54:41 26 4
gpt4 key购买 nike

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

最佳答案

您可以修改 BookingSerializer__init__ 方法中的字段。初始化后,可以在 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()

关于python - DjangoRestFramework 序列化程序的条件字段要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35721483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com