我有这个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()应该被调用"例外。如何正确访问拍卖场价值?
答案 0 :(得分:2)
如果您想根据另一个字段的值检查一个字段,则应使用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)