File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -37,6 +37,43 @@ Field(sa_column=Column(PydanticJSONB(List[SomeModel])))
37
37
Field(sa_column = Column(PydanticJSONB(Dict[str , SomeModel])))
38
38
```
39
39
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
+
40
77
## Requirements
41
78
42
79
* PostgreSQL (for full ` JSONB ` support).
You can’t perform that action at this time.
0 commit comments