Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from sqlmodel import Field, SQLModel, create_engine
from datetime import datetime
from fastapi import FastAPI
from sqlmodel import Session
from pydantic import BaseModel
import uuid

sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url, echo=True)

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


class HeroBase(BaseModel):
    name: str
    power: str
    weakness: str

class Hero(SQLModel, table=True):
    id: str = Field(default=None, primary_key=True)
    name: str
    power: str
    weakness: str

api = FastAPI()

@api.on_event("startup")
async def startup_event():
    create_db_and_tables()

@api.post("/heroes")
async def create_hero(hero: Hero):
    with Session(engine) as session:
        hero.id = str(uuid.uuid4())
        session.add(hero)
        session.commit()
        session.refresh(hero)
        return hero

Description

based on these docs: https://sqlmodel.tiangolo.com/tutorial/fastapi/simple-hero-api/

if you run the above code and try to post the following

{
    "name": "hero"
}

you should expect to see

{
    "detail": [
        {
            "type": "missing",
            "loc": [
                "body",
                "power"
            ],
            "msg": "Field required",
            "input": {
                "name": "hero"
            }
        },
        {
            "type": "missing",
            "loc": [
                "body",
                "weakness"
            ],
            "msg": "Field required",
            "input": {
                "name": "hero"
            }
        }
    ]
}

in fact, when you switch the body python type for that API from Hero to HeroBase which uses BaseModel from pydantic you do.

but if you run it with Hero as is outlined in the docs, you get a 500 internal server error and a non null constraint.

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: hero.power
[SQL: INSERT INTO hero (id, name, power, weakness) VALUES (?, ?, ?, ?)]
[parameters: ('c40b0cdf-2a3d-402d-90c5-321c01740190', 'hero', None, None)]
(Background on this error at: https://sqlalche.me/e/20/gkpj)

which means fastapis built in validation is not working allowing the model to be read even with missing fields causing the database error. which directly contradicts this line from the docs

Because FastAPI is based on Pydantic, it will use the same model (the Pydantic part) to do automatic data validation and conversion from the JSON request to an object that is an actual instance of the Hero class.

Operating System

macOS

Operating System Details

No response

SQLModel Version

0.0.27

Python Version

Python 3.13.3

Additional Context

No response

You must be logged in to vote

You shouldn't use table-model (with table=True) for validation. Create base class with common fields (excluding relationships) and inherit input validation model and table-model from that base class.

See: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance

Replies: 1 comment · 1 reply

Comment options

You shouldn't use table-model (with table=True) for validation. Create base class with common fields (excluding relationships) and inherit input validation model and table-model from that base class.

See: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance

You must be logged in to vote
1 reply
@andrewnathanco
Comment options

thank you, this section of docs is a bit misleading, https://sqlmodel.tiangolo.com/tutorial/fastapi/simple-hero-api/#create-heroes-path-operation as it implies that it will work out of the box, but your answer should fix it

Answer selected by andrewnathanco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.