[Django]-Serializer field validation and how to check if value exist?

2👍

Try adding this code

create or update in views

if User.objects.filter(email=self.request.data['email']).exists():
    return Response({"error": "This email id already exists."})

2👍

You could try raising a ValidationError which is part of the serializers library:

from rest_framework import serializers

def update(self, instance, validated_data):
  # If `self.request.data["email"]` works
  if User.objects.filter(email=self.request.data["email"]).exists():
    raise serializers.ValidationError("This email already exists.")

  # If `self.request.data["email"]` doesn't work
  new_email = self.initial_data.get("email"):
  if new_email and User.objects.filter(email=new_email).exists():
    raise serializers.ValidationError("This email already exists.")

  # Save and return the modified instanced

or if you unique=True to the email field, it will raise an IntegrityError so you don’t need to do any further checks. You simply catch the error and handle it yourself.

1👍

I assume you want email to be unique. Then you should add unique=True to your user model’s email field.

class YourUserModel(AbstractUser):
    email = models.EmailField(unique=True)

After you make email a unique field, your database will not allow to add another entry with the same email and it will raise IntegrityError. You can catch this error and return a better error message to your user. Like this:

try:
    if serializer.is_valid(raise_exception=False):
        serializer.save()
except IntegrityError:
    return Response(data={'message':'that email is in use'}, status=HTTP_400_BAD_REQUEST)

Leave a comment