Coverage for docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.7.1, created at 2025-03-24 00:02 +0000

1from sqlmodel import Field, Relationship, SQLModel, create_engine 1abcd

2 

3 

4class Weapon(SQLModel, table=True): 1abcd

5 id: int | None = Field(default=None, primary_key=True) 1abcd

6 name: str = Field(index=True) 1abcd

7 

8 hero: "Hero" = Relationship(back_populates="weapon") 1abcd

9 

10 

11class Power(SQLModel, table=True): 1abcd

12 id: int | None = Field(default=None, primary_key=True) 1abcd

13 name: str = Field(index=True) 1abcd

14 

15 hero_id: int = Field(foreign_key="hero.id") 1abcd

16 hero: "Hero" = Relationship(back_populates="powers") 1abcd

17 

18 

19class Team(SQLModel, table=True): 1abcd

20 id: int | None = Field(default=None, primary_key=True) 1abcd

21 name: str = Field(index=True) 1abcd

22 headquarters: str 1abcd

23 

24 heroes: list["Hero"] = Relationship(back_populates="team") 1abcd

25 

26 

27class Hero(SQLModel, table=True): 1abcd

28 id: int | None = Field(default=None, primary_key=True) 1abcd

29 name: str = Field(index=True) 1abcd

30 secret_name: str 1abcd

31 age: int | None = Field(default=None, index=True) 1abcd

32 

33 team_id: int | None = Field(default=None, foreign_key="team.id") 1abcd

34 team: Team | None = Relationship(back_populates="heroes") 1abcd

35 

36 weapon_id: int | None = Field(default=None, foreign_key="weapon.id") 1abcd

37 weapon: Weapon | None = Relationship(back_populates="hero") 1abcd

38 

39 powers: list[Power] = Relationship(back_populates="hero") 1abcd

40 

41 

42sqlite_file_name = "database.db" 1abcd

43sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcd

44 

45engine = create_engine(sqlite_url, echo=True) 1abcd

46 

47 

48def create_db_and_tables(): 1abcd

49 SQLModel.metadata.create_all(engine) 1abcd

50 

51 

52def main(): 1abcd

53 create_db_and_tables() 1abcd

54 

55 

56if __name__ == "__main__": 1abcd

57 main()