0

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

1 Answer 1

2

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

from rest_framework.validators import UniqueValidator
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @catavaran they have not mentioned anywhere in validations page
Yep, documentation is not clear here. They have a small link to the validators.py source at the top right corner of the page django-rest-framework.org/api-guide/validators
Or use IDE with auto import feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.