Coverage for docs_src / tutorial / relation / many_to_many_relationship / tutorial000.py: 100%
49 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-07 08:37 +0000
1import os 1abcdef
2from typing import Optional 1abcdef
4from mongodb_odm import ( 1abcdef
5 ASCENDING,
6 Document,
7 Field,
8 IndexModel,
9 ODMObjectId,
10 Relationship,
11 apply_indexes,
12 connect,
13)
16class Country(Document): 1abcdef
17 name: str 1abcdef
20class Skill(Document): 1abcdef
21 name: str 1abcdef
24class Player(Document): 1abcdef
25 name: str 1abcdef
26 country_id: ODMObjectId 1abcdef
28 country: Optional[Country] = Relationship(local_field="country_id") 1abcdef
30 class ODMConfig(Document.ODMConfig): 1abcdef
31 indexes = [ 1abcdef
32 IndexModel([("country_id", ASCENDING)]),
33 ]
36class PlayerSkill(Document): 1abcdef
37 player_id: ODMObjectId 1abcdef
38 skill_id: ODMObjectId 1abcdef
39 rating: int = Field(default=0, ge=1, le=100) 1abcdef
41 player: Optional[Player] = Relationship(local_field="player_id") 1abcdef
42 skill: Optional[Skill] = Relationship(local_field="skill_id") 1abcdef
44 class ODMConfig(Document.ODMConfig): 1abcdef
45 indexes = [ 1abcdef
46 IndexModel(
47 [("player_id", ASCENDING), ("skill_id", ASCENDING)],
48 unique=True,
49 ),
50 ]
53def insert_data(): 1abcdef
54 brazil = Country(name="Brazil").create() 1abcdef
55 argentina = Country(name="Argentina").create() 1abcdef
56 france = Country(name="France").create() 1abcdef
58 catching = Skill(name="Catching") 1abcdef
59 running = Skill(name="Running") 1abcdef
60 kicking = Skill(name="Kicking") 1abcdef
62 pele = Player(name="Pelé", country_id=brazil.id).create() 1abcdef
63 PlayerSkill(player_id=pele.id, skill_id=catching.id, rating=49).create() 1abcdef
64 PlayerSkill(player_id=pele.id, skill_id=kicking.id, rating=49).create() 1abcdef
66 maradona = Player(name="Diego Maradona", country_id=argentina.id).create() 1abcdef
67 PlayerSkill(player_id=maradona.id, skill_id=catching.id, rating=48).create() 1abcdef
68 PlayerSkill(player_id=maradona.id, skill_id=kicking.id, rating=49).create() 1abcdef
70 zidane = Player(name="Zinedine Zidane", country_id=france.id).create() 1abcdef
71 PlayerSkill(player_id=zidane.id, skill_id=running.id, rating=42).create() 1abcdef
72 PlayerSkill(player_id=zidane.id, skill_id=kicking.id, rating=42).create() 1abcdef
75def read_data(): 1abcdef
76 pele = Player.get({Player.name: "Pelé"}) 1abcdef
77 skills = list(PlayerSkill.find({"player_id": pele.id})) 1abcdef
79 print(pele) 1abcdef
80 print(skills) 1abcdef
83def configuration(): 1abcdef
84 connect(os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb")) 1abcdef
85 apply_indexes() 1abcdef
88def main(): 1abcdef
89 configuration() 1abcdef
90 insert_data() 1abcdef
91 read_data() 1abcdef
94if __name__ == "__main__": 1abcdef
95 main()