How to use HttpUrl in SqlModel? I get a SqlAlchemy error #956
Unanswered
vinodkumars
asked this question in
Questions
Replies: 1 comment
-
I ran into the same issue and ended up using a custom Full example: from datetime import datetime
from typing import Optional
from pydantic import ConfigDict, HttpUrl
from pydantic.alias_generators import to_camel
from sqlalchemy import func
from sqlalchemy.types import String, TypeDecorator, DateTime
from sqlmodel import Field, SQLModel
from .config import settings
class HttpUrlType(TypeDecorator):
impl = String(2083)
cache_ok = True
python_type = HttpUrl
def process_bind_param(self, value, dialect) -> str:
return str(value)
def process_result_value(self, value, dialect) -> HttpUrl:
return HttpUrl(url=value)
def process_literal_param(self, value, dialect) -> str:
return str(value)
class UrlBase(SQLModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True,
from_attributes=True,
)
url: HttpUrl = Field(
index=True,
unique=True,
nullable=False,
sa_type=HttpUrlType,
)
class Url(UrlBase, table=True):
__tablename__ = "urls"
id: str = Field(
max_length=settings.url_id_length,
min_length=settings.url_id_length,
primary_key=True,
nullable=False,
)
visits: int = Field(default=0)
created_at: Optional[datetime] = Field(
default=None,
sa_type=DateTime(timezone=True),
sa_column_kwargs={
"server_default": func.now(), # pylint: disable=E1102
},
)
updated_at: Optional[datetime] = Field(
default=None,
sa_type=DateTime(timezone=True),
sa_column_kwargs={
"onupdate": func.now(), # pylint: disable=E1102
},
)
class UrlCreate(UrlBase):
pass
class UrlRead(UrlBase):
id: str
visits: int
created_at: datetime
updated_at: Optional[datetime] |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
When I enter a valid url like
https://example.com
I get an error from SqlAlchemy. Here's the error:Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.18
Python Version
3.11
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions