I am new to FastAPI. How can i create record in db using sqlmodel and databases packages?
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship(back_populates="heroes")
@app.post("/hero", description="Create new hero")
async def create_hero(data: Hero):
hero = Hero(**data.dict())
q = insert(Hero).values(**hero.dict())
h_id = await db.execute(q)
When i finally try to do this, it shows me:
asyncpg.exceptions.NotNullViolationError: null value in column "id" of relation "hero" violates not-null constraint
DETAIL: Failing row contains (null, spider, black, 18, null).
Referring to the sqlmodel docs, id will be set automatically, but using sqlmodel.Session. How to do the same thing with
import databases
db = databases.Database("postgresql+asyncpg://postgres:postgres@localhost:5432/testdb")
insertanddbin yourcreate_herofunction? Usually you'd work with an SQLAlchemy session to add these objects as shown in sqlmodel.tiangolo.com/tutorial/automatic-id-none-refresh/…Session, and trying to mix it with thedatabasespackage will probably lead to headaches.databasesinto the mix? SQLModel is designed to work with an SQLAlchemy session (async support in SQLAlchemy was introduced as part of 1.4: docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html)