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

33 statements  

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

1from typing import Optional 1abcd

2 

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

4 

5 

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

7 id: Optional[int] = Field(default=None, primary_key=True) 1abcd

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

9 

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

11 

12 

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

14 id: Optional[int] = Field(default=None, primary_key=True) 1abcd

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

16 

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

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

19 

20 

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

22 id: Optional[int] = Field(default=None, primary_key=True) 1abcd

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

24 headquarters: str 1abcd

25 

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

27 

28 

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

30 id: Optional[int] = Field(default=None, primary_key=True) 1abcd

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

32 secret_name: str 1abcd

33 age: Optional[int] = Field(default=None, index=True) 1abcd

34 

35 team_id: Optional[int] = Field(default=None, foreign_key="team.id") 1abcd

36 team: Optional[Team] = Relationship(back_populates="heroes") 1abcd

37 

38 weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") 1abcd

39 weapon: Optional[Weapon] = Relationship(back_populates="hero") 1abcd

40 

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

42 

43 

44sqlite_file_name = "database.db" 1abcd

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

46 

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

48 

49 

50def create_db_and_tables(): 1abcd

51 SQLModel.metadata.create_all(engine) 1abcd

52 

53 

54def main(): 1abcd

55 create_db_and_tables() 1abcd

56 

57 

58if __name__ == "__main__": 1abcd

59 main()