Skip to content

Commit bcd8689

Browse files
committed
=Added examples for creating, storing, and retrieving data
1 parent d329a50 commit bcd8689

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/advanced/pydantic-jsonb.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,43 @@ Field(sa_column=Column(PydanticJSONB(List[SomeModel])))
3737
Field(sa_column=Column(PydanticJSONB(Dict[str, SomeModel])))
3838
```
3939

40+
## Create & Store Data
41+
42+
Here's how to create and store data with Pydantic models in JSONB columns:
43+
44+
```python
45+
from sqlmodel import Session, create_engine
46+
47+
engine = create_engine("postgresql://user:password@localhost/db")
48+
49+
# Insert a User with an Address
50+
with Session(engine) as session:
51+
user = User(
52+
name="John Doe",
53+
address=Address(street="123 Main St", city="New York")
54+
)
55+
session.add(user)
56+
session.commit()
57+
```
58+
59+
## Retrieve & Use Data
60+
61+
When you retrieve the data, it's automatically converted back to a Pydantic model:
62+
63+
```python
64+
with Session(engine) as session:
65+
user = session.query(User).first()
66+
print(user.address.street) # "123 Main St"
67+
print(user.address.city) # "New York"
68+
print(type(user.address)) # <class '__main__.Address'>
69+
```
70+
71+
Result:
72+
✅ No need for `Address(**user.address)` – it's already an `Address` instance!
73+
✅ Automatic conversion between JSONB and Pydantic models.
74+
75+
This simplifies handling structured data in SQLModel, making JSONB storage seamless and ergonomic. 🚀
76+
4077
## Requirements
4178

4279
* PostgreSQL (for full `JSONB` support).

0 commit comments

Comments
 (0)