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")