Skip to content

There seems to be a bug in using model with aliased fields to define request body  #374

Open
@boh5

Description

@boh5

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue 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 typing import Optional

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from sqlmodel import Field, Session, SQLModel, create_engine, select


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    secret_name: str = Field(alias='secretName')
    age: Optional[int] = Field(default=None, index=True)


class HeroPydantic(BaseModel):
    id: Optional[int] = Field(default=None)
    name: str = Field()
    secret_name: str = Field(alias='secretName')
    age: Optional[int] = Field(default=None)


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


connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)


app = FastAPI()


@app.post("/heroes/")
def create_hero(hero: Hero):
    with Session(engine) as session:
        session.add(hero)
        session.commit()
        session.refresh(hero)
        return hero


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8081)

Description

  1. Create Hero model, the secret_name field aliased to secretName
  2. Post data
{
  "name": "string",
  "secretName": "string",
  "age": 0
}
  1. Then get hero.secret_name is None
  2. If I replace hero: Hero to hero: HeroPydantic, the hero.secret_name can get correct value from post data. But the strainge thing is that I can get correct hero.secret_name by hero: Hero = Hero.parse_obj(hero.dict(by_alias=True))

So it seems that alias argument in sqlmodel seems not working for converting body from post data, I have to write two models in order to achieve that.

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.7.6

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions