Proper way of dealing with unique constraints

I'm trying to find a way to check if an user's Username or Email already exists in the database, then return a ValidationError with the appropiate error message. However i see no way of doing this without calling multiple queries or making it look weird (adding a serializer within a service)...

Is there a coding practice for doing this properly? This is just one of many possible usecases:

    users = User.objects.filter(Q(email=email) | Q(username=username))
    if users.exists():
        for user in users:  # There could be two
            if user.email == email:
                raise ValidationError('Email already exists.')

            else:
                raise ValidationError('Username already exists.')```
Back to Top