Rohan
Rohan

Reputation: 60

Validation in django rest framework

I am trying to validate existing record in django rest framework and following the link

In my serializer class I have my class like .

from django.forms import widgets
from rest_framework import serializers
from models import Part

class PartSerializer(serializers.Serializer):

    part_id = serializers.CharField(required=True, validators=[UniqueValidator(queryset=Part.objects.all())] )
    capacity = serializers.IntegerField(required=True)
    price = serializers.IntegerField(required=True)


    def create(self, validated_data):

        """
        Create and return a new `Part` instance, given the validated data.
        """
      #  try:part_exist = Part.objects.get(part_id = validated_data['part_id'])
      #  except:part_exist = None
      #  if part_exist:
      #      raise  serializers.ValidationError('Part name already exist.')
      #  else:
        return Part.objects.create(**validated_data)

But I am always getting error name 'UniqueValidator' is not defined

I don't know how to import this as it is not mentioned in doc .Please help me out how to do this .And if it is not possible should I write own validation logic under views ?

Thanks

Upvotes: 0

Views: 2211

Answers (1)

catavaran
catavaran

Reputation: 45585

You should import the UniqueValidator from the rest_framework.validators module:

from rest_framework.validators import UniqueValidator

Upvotes: 2

Related Questions