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

32 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

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

2 

3 

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

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

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

7 

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

9 

10 

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

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

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

14 

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

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

17 

18 

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

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

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

22 headquarters: str 1abc

23 

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

25 

26 

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

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

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

30 secret_name: str 1abc

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

32 

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

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

35 

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

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

38 

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

40 

41 

42sqlite_file_name = "database.db" 1abc

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

44 

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

46 

47 

48def create_db_and_tables(): 1abc

49 SQLModel.metadata.create_all(engine) 1abc

50 

51 

52def main(): 1abc

53 create_db_and_tables() 1abc

54 

55 

56if __name__ == "__main__": 1abc

57 main()