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

33 statements  

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

1from typing import List, Optional 1abcdef

2 

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

4 

5 

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

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

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

9 

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

11 

12 

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

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

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

16 

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

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

19 

20 

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

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

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

24 headquarters: str 1abcdef

25 

26 heroes: List["Hero"] = Relationship(back_populates="team") 1abcdef

27 

28 

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

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

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

32 secret_name: str 1abcdef

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

34 

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

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

37 

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

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

40 

41 powers: List[Power] = Relationship(back_populates="hero") 1abcdef

42 

43 

44sqlite_file_name = "database.db" 1abcdef

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

46 

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

48 

49 

50def create_db_and_tables(): 1abcdef

51 SQLModel.metadata.create_all(engine) 1abcdef

52 

53 

54def main(): 1abcdef

55 create_db_and_tables() 1abcdef

56 

57 

58if __name__ == "__main__": 1abcdef

59 main()