Coverage for docs_src / tutorial / relation / many_to_many_relationship / tutorial001.py: 100%
37 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 BaseModel,
7 Document,
8 Field,
9 IndexModel,
10 ODMObjectId,
11 Relationship,
12 apply_indexes,
13 connect,
14)
17class Country(Document): 1abcdef
18 name: str 1abcdef
21class Skill(Document): 1abcdef
22 name: str 1abcdef
25class EmbeddedSkill(BaseModel): 1abcdef
26 skill_id: ODMObjectId 1abcdef
27 rating: int = Field(default=0, ge=1, le=100) 1abcdef
30class Player(Document): 1abcdef
31 name: str 1abcdef
32 country_id: ODMObjectId 1abcdef
33 skills: list[EmbeddedSkill] = [] 1abcdef
35 country: Optional[Country] = Relationship(local_field="country_id") 1abcdef
37 class ODMConfig(Document.ODMConfig): 1abcdef
38 indexes = [ 1abcdef
39 IndexModel([("country_id", ASCENDING)]),
40 ]
43def insert_data(): 1abcdef
44 brazil = Country(name="Brazil").create() 1abcdef
45 argentina = Country(name="Argentina").create() 1abcdef
46 france = Country(name="France").create() 1abcdef
48 catching = Skill(name="Catching") 1abcdef
49 running = Skill(name="Running") 1abcdef
50 kicking = Skill(name="Kicking") 1abcdef
52 Player( 1abcdef
53 name="Pelé",
54 country_id=brazil.id,
55 skills=[
56 EmbeddedSkill(skill_id=catching.id, rating=49),
57 EmbeddedSkill(skill_id=kicking.id, rating=49),
58 ],
59 ).create()
60 Player( 1abcdef
61 name="Diego Maradona",
62 country_id=argentina.id,
63 skills=[
64 EmbeddedSkill(skill_id=catching.id, rating=48),
65 EmbeddedSkill(skill_id=kicking.id, rating=49),
66 ],
67 ).create()
68 Player( 1abcdef
69 name="Zinedine Zidane",
70 country_id=france.id,
71 skills=[
72 EmbeddedSkill(skill_id=running.id, rating=42),
73 EmbeddedSkill(skill_id=kicking.id, rating=42),
74 ],
75 ).create()
78def read_data(): 1abcdef
79 pele = Player.get({Player.name: "Pelé"}) 1abcdef
80 print(pele) 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()