First Check
Commit to Help
Example Code
from typing import List, Optional
from sqlmodel import Field, Relationship, Session, SQLModel, create_engine
from pydantic import BaseModel
class Team(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
heroes: List["Hero"] = Relationship(back_populates="team")
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship(back_populates="heroes")
class Hero2(BaseModel):
id: int
team: Team
class Team2(BaseModel):
id: int
heroes: List["Hero2"]
# What I would like to be able to do
d = {"id": 123, "team": {"id": 124}} # fails
# d = {"id": 123, "team": Team(**{"id": 124})} # succeeds
h = Hero(**d)
print(h)
# The same idea but using vanilla Pydantic models
d2 = {"id": 123, "team": {"id": 124}}
h2 = Hero2(**d2)
print(h2)
Description
In Pydantic it is possible to instantiate objects directly from dicts (i.e. JSON) via ClassName(**dict). This also works for objects with nested objects (i.e. relationships in SQLModel). Is it possible to do the same in SQLModel? I would like to take a JSON like {"id": 123, "relationship_obj": {"id": 456, ...}} and have SQLModel correctly create the relationship model based on the type of the field & the key of the dict passed in.
The error received is:
File "/.../venv/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", lin
e 1729, in emit_backref_from_scalar_set_event
instance_state(child),
AttributeError: 'dict' object has no attribute '_sa_instance_state'
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
Python 3.9.5
Additional Context
No response
First Check
Commit to Help
Example Code
Description
In Pydantic it is possible to instantiate objects directly from dicts (i.e. JSON) via
ClassName(**dict). This also works for objects with nested objects (i.e. relationships in SQLModel). Is it possible to do the same in SQLModel? I would like to take a JSON like{"id": 123, "relationship_obj": {"id": 456, ...}}and have SQLModel correctly create the relationship model based on the type of the field & the key of the dict passed in.The error received is:
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
Python 3.9.5
Additional Context
No response