Advice for unique=True, max_length=30, min_length=3, that are causing a few problems #1132
-
First Check
Commit to Help
Example Codeclass Role(str, Enum): admin = "admin" superuser = "superuser" customer = "customer" class User(SQLModel, table=True): __tablename__ = "users" uid: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) email: str = Field(unique=True, max_length=30, min_length=3) username: str = Field(unique=True, max_length=30, min_length=3) date_joined: datetime = Field(default_factory=datetime.now) updated_at: datetime = Field(default_factory=datetime.now) is_staff: bool = Field(default=False) is_superuser: bool = Field(default=False) is_active: bool = Field(default=True) first_name: str | None = Field(default=None, max_length=20, min_length=2) last_name: str | None = Field(default=None, max_length=20, min_length=2) profile_picture: str | None = Field(default=None) phone: str | None = Field(default=None, max_length=20, min_length=8) role: Role = Field(default=Role.customer) agree_to_terms: bool = Field(default=False) password_hash: str = Field(default=None) todos: list["Todo"] = Relationship(back_populates="owner") def __repr__(self): return f"<User {self.username}>" Descriptionunique=True, max_length=30, min_length=3 are not working in sqlmodel Operating SystemWindows Operating System DetailsNo response SQLModel Versionsqlmodel==0.0.22 Python Version3.12 Additional ContextI am sorry if i didn't fill in the notes correctly. I am coming from django and currently learning about sqlmodel and fastapi. I love it! I think it is great, but i run into a few problems. I am coding along with one udemy course. The author creates the database.py from sqlmodel import SQLModel, create_engine, Field, Session import models sqlite_filename = 'database.db' sqlite_url = f"sqlite:///{sqlite_filename}" engine = create_engine(sqlite_url, echo=True) if __name__ == '__main__': SQLModel.metadata.create_all(engine) This is models.py from sqlmodel import SQLModel, Field from typing import Optional class Category(SQLModel, table=True): id: Optional[int] = Field(primary_key=True, default=None) name: str = Field(index=True, unique=True, max_length=30, min_length=3) This is main.py from fastapi import FastAPI from sqlmodel import SQLModel, Session from models import Category, CreateCategory from database import engine from fastapi.responses import HTMLResponse # define main app name app = FastAPI() # define database session name session = Session(bind=engine) @app.post('/category/create') async def create_category(category:Category): new_category = Category(name=category.name) with Session(engine) as session: session.add(new_category) session.commit() session.refresh(new_category) return new_category Now in the docs i saw that the version 0.0.7 has the unique validation working but i tried it and it doesn't, so i am sure the mistake is somewhere on my side. So my code is the same. But i don't get validations for unique=True, max_length=30, min_length=3, and he does. I also tried to create one model for creating the object, like this: class CreateCategory(SQLModel): name: str = Field(unique=True, max_length=30, min_length=3, default='demo') Then i use that in the async def with category:CreateCategory and now the min and max validations are working, but the unique=True still doesn't work. So i am confused, i can't continue with the learning process until i learn this. If sqlmodel is to shorten the development time and act as a database model and validation model, why is there a need to create additional schemas for validation, especially if they are not working / not validating? Why can't we just use sqlalchemy and pydantic if there is a problem with sqlmodel? Can someone please help explain this? Thank you p.s. in the field above, i wrote a User model based on my Django projects. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The fact that validation doesn't work for "table" models is a limitation of SQLModel, but it doesn't mean that it's useless. class CategoryBase(SQLModel): name: str = Field(index=True, unique=True, max_length=30, min_length=3) class Category(CategoryBase, table=True): id: Optional[int] = Field(primary_key=True, default=None) class CreateCategory(CategoryBase): pass The code example below works. It creates unique constraint, and it validates input values. from typing import Optional from fastapi import FastAPI from sqlmodel import Field, Session, SQLModel, create_engine class CategoryBase(SQLModel): name: str = Field(index=True, unique=True, max_length=30, min_length=3) class Category(CategoryBase, table=True): id: Optional[int] = Field(primary_key=True, default=None) class CreateCategory(CategoryBase): pass sqlite_filename = 'database.db' sqlite_url = f"sqlite:///{sqlite_filename}" engine = create_engine(sqlite_url, echo=True) SQLModel.metadata.create_all(engine) # define main app name app = FastAPI() # define database session name session = Session(bind=engine) @app.post('/category/create') async def create_category(category:CreateCategory): new_category = Category(name=category.name) with Session(engine) as session: session.add(new_category) session.commit() session.refresh(new_category) return new_category |
Beta Was this translation helpful? Give feedback.
The fact that validation doesn't work for "table" models is a limitation of SQLModel, but it doesn't mean that it's useless.
It still helps avoid duplication (no need to duplicate fields):
The code example below works. It creates unique constraint, and it validates input values.