1

for example I have a django model as

class User(models.Model):
    email = models.EmailField(required=True, unique=True)

Isnt it redundant and against DRY principle to validate again in the ModelSerializer as following?

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
    def validate_email(self, email):
        try:
            User.objects.get(email=email)
            raise serializers.ValidationError("Email address already used")
        except User.DoesNotExist:
            return email

The validate_email method feels kind of against the DRY PRINCIPLE and wrong in this context since we have to access Database to validate in this method. please correct me.

udeep shrestha
  • 912
  • 11
  • 11

1 Answers1

2

You don't have to validate the data again in the serializer if you have validation already in model level. In your case, the difference is the error message that you'll get from the API.

By default, DRF return {'field_name':['This field must be unique']} response in case of unique validation fail

Quoting @dirkgroten's comment

Note that to override the generic error message, you don't need to re-validate either. Just use the extra_kwargs attribute on the serializer as explained here

JPG
  • 82,442
  • 19
  • 127
  • 206
  • 2
    Note that to override the generic error message, you don't need to re-validate either. Just use the `extra_kwargs` attribute on the serializer as explained [here](https://stackoverflow.com/a/26975268/1252711) – dirkgroten Dec 17 '19 at 13:52
  • @dirkgroten Thanks for the info :) – JPG Dec 17 '19 at 16:55