Dmitry Sazhnev
Dmitry Sazhnev

Reputation: 383

How do I get serializer field value inside serializer

I have this 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()

But it throws throws "is_valid() should be called" exception. How do I properly access auction field value?

Upvotes: 2

Views: 2473

Answers (1)

user8060120
user8060120

Reputation:

if you want to check one field based on value of the other you just should use 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)

Upvotes: 2

Related Questions