|
1 |
| -from typing import Optional |
| 1 | +from typing import List, Optional |
2 | 2 |
|
3 | 3 | import pytest
|
4 | 4 | from sqlalchemy.exc import IntegrityError
|
5 |
| -from sqlmodel import Field, Session, SQLModel, create_engine |
| 5 | +from sqlalchemy.orm import RelationshipProperty |
| 6 | +from sqlmodel import Field, Relationship, Session, SQLModel, create_engine |
6 | 7 |
|
7 | 8 |
|
8 | 9 | def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel):
|
@@ -91,3 +92,36 @@ class Hero(SQLModel, table=True):
|
91 | 92 | session.add(hero_2)
|
92 | 93 | session.commit()
|
93 | 94 | session.refresh(hero_2)
|
| 95 | + |
| 96 | + |
| 97 | +def test_sa_relationship(clear_sqlmodel): |
| 98 | + """Test https://github.com/tiangolo/sqlmodel/issues/315#issuecomment-1272122306""" |
| 99 | + |
| 100 | + class Team(SQLModel, table=True): |
| 101 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 102 | + name: str = Field(unique=True) |
| 103 | + heroes: List["Hero"] = Relationship( |
| 104 | + sa_relationship=RelationshipProperty("Hero", back_populates="team") |
| 105 | + ) |
| 106 | + |
| 107 | + class Hero(SQLModel, table=True): |
| 108 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 109 | + name: str = Field(unique=True) |
| 110 | + team_id: Optional[int] = Field(default=None, foreign_key="team.id") |
| 111 | + team: Optional[Team] = Relationship( |
| 112 | + sa_relationship=RelationshipProperty("Team", back_populates="heroes") |
| 113 | + ) |
| 114 | + |
| 115 | + team_preventers = Team(name="Preventers") |
| 116 | + hero_rusty_man = Hero(name="Rusty-Man", team=team_preventers) |
| 117 | + |
| 118 | + engine = create_engine("sqlite://", echo=True) |
| 119 | + |
| 120 | + SQLModel.metadata.create_all(engine) |
| 121 | + |
| 122 | + with Session(engine) as session: |
| 123 | + session.add(hero_rusty_man) |
| 124 | + session.commit() |
| 125 | + session.refresh(hero_rusty_man) |
| 126 | + # The next statement should not raise an AttributeError |
| 127 | + assert hero_rusty_man.team.name == "Preventers" |
0 commit comments