You can achieve this by writing a functional validator like so:
from typing import Annotated
from pydantic import BaseModel, HttpUrl, AfterValidator
HttpStr = Annotated[HttpUrl, AfterValidator(str)]
class MyModel(BaseModel):
url: HttpStr
m1 = MyModel(url="https://hello.com")
assert m1.url == "https://hello.com/"
m2 = MyModel(url="https://hello[.]com") # raises ValidationError("Input should be a valid URL, invalid domain character")
In this example we leverage HttpUrl annotated type, and then add an AfterValidator to coerce the Url back into a string.
However, quickly shimming through the SQLAlchemy documentation it looks like this might be a common problem with a documented workaround. Potentially this might be more elegant approach to your specific problem?
A frequent need is to force the “string” version of a type, that is the one rendered in a CREATE TABLE statement or other SQL function like CAST, to be changed.
https://docs.sqlalchemy.org/en/20/core/custom_types.html#overriding-type-compilation