gpt4 book ai didi

django - 如何在序列化程序中获取序列化程序字段值

转载 作者:行者123 更新时间:2023-12-04 16:02:33 25 4
gpt4 key购买 nike

我有这个 ModelSerializer:

class BidSerializer(serializers.ModelSerializer):

class Meta:
model = Bid
fields = '__all__'

def validate_amount(self, value):
auction = Auction.objects.get(id=self.validated_data['auction'])
if auction.price_step % value:
raise serializers.ValidationError()

但它抛出“is_valid() should be called”异常。如何正确访问拍卖字段值?

最佳答案

如果你想根据另一个字段的值检查一个字段,你应该使用 object-level-validation

class BidSerializer(serializers.ModelSerializer):

class Meta:
model = Bid
fields = '__all__'

def validate(self, data):
auction = Auction.objects.get(id=data['auction'])
amount = data.get('amount')
if auction.price_step % amount:
msg = {'amount' : ['this field is not valid']}
raise serializers.ValidationError(msg)

关于django - 如何在序列化程序中获取序列化程序字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063697/

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