|
1 | 1 | import datetime |
2 | 2 | from typing import Optional |
3 | 3 |
|
| 4 | +import pydantic |
4 | 5 | from sqlalchemy import DateTime, func |
5 | 6 | from sqlalchemy.orm import declared_attr, relationship |
6 | 7 | from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select |
| 8 | +from sqlmodel._compat import IS_PYDANTIC_V2 |
7 | 9 |
|
8 | 10 |
|
9 | | -def test_relationship_inheritance() -> None: |
| 11 | +def test_inherit_relationship(clear_sqlmodel) -> None: |
10 | 12 | def now(): |
11 | 13 | return datetime.datetime.now(tz=datetime.timezone.utc) |
12 | 14 |
|
@@ -90,3 +92,57 @@ class Document(CreatedUpdatedMixin, table=True): |
90 | 92 | doc = session.exec(select(Document)).one() |
91 | 93 | assert doc.created_by.name == "Jane" |
92 | 94 | assert doc.updated_by.name == "John" |
| 95 | + |
| 96 | + |
| 97 | +def test_inherit_relationship_model_validate(clear_sqlmodel) -> None: |
| 98 | + class User(SQLModel, table=True): |
| 99 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 100 | + |
| 101 | + class Mixin(SQLModel): |
| 102 | + owner_id: Optional[int] = Field(default=None, foreign_key="user.id") |
| 103 | + owner: Optional[User] = Relationship( |
| 104 | + sa_relationship=declared_attr( |
| 105 | + lambda cls: relationship(User, foreign_keys=cls.owner_id) |
| 106 | + ) |
| 107 | + ) |
| 108 | + |
| 109 | + class Asset(Mixin, table=True): |
| 110 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 111 | + |
| 112 | + class AssetCreate(pydantic.BaseModel): |
| 113 | + pass |
| 114 | + |
| 115 | + asset_create = AssetCreate() |
| 116 | + |
| 117 | + engine = create_engine("sqlite://") |
| 118 | + |
| 119 | + SQLModel.metadata.create_all(engine) |
| 120 | + |
| 121 | + user = User() |
| 122 | + |
| 123 | + # Owner must be optional |
| 124 | + asset = Asset.model_validate(asset_create) |
| 125 | + with Session(engine) as session: |
| 126 | + session.add(asset) |
| 127 | + session.commit() |
| 128 | + session.refresh(asset) |
| 129 | + assert asset.id is not None |
| 130 | + assert asset.owner_id is None |
| 131 | + assert asset.owner is None |
| 132 | + |
| 133 | + # When set, owner must be saved |
| 134 | + # |
| 135 | + # Under Pydantic V2, relationship fields set it `model_validate` are not saved, |
| 136 | + # with or without inheritance. Consider it a known issue. |
| 137 | + # |
| 138 | + if IS_PYDANTIC_V2: |
| 139 | + asset = Asset.model_validate(asset_create, update={"owner": user}) |
| 140 | + with Session(engine) as session: |
| 141 | + session.add(asset) |
| 142 | + session.commit() |
| 143 | + session.refresh(asset) |
| 144 | + session.refresh(user) |
| 145 | + assert asset.id is not None |
| 146 | + assert user.id is not None |
| 147 | + assert asset.owner_id == user.id |
| 148 | + assert asset.owner.id == user.id |
0 commit comments