MCPcopy Index your code
hub / github.com/tortoise/tortoise-orm / run

Function run

examples/group_by.py:19–85  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

17
18
19async def run():
20 await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
21 await Tortoise.generate_schemas()
22
23 a1 = await Author.create(name="author1")
24 a2 = await Author.create(name="author2")
25 for i in range(10):
26 await Book.create(name=f"book{i}", author=a1, rating=i)
27 for i in range(5):
28 await Book.create(name=f"book{i}", author=a2, rating=i)
29
30 ret = await Book.annotate(count=Count("id")).group_by("author_id").values("author_id", "count")
31 print(ret)
32 # >>> [{'author_id': 1, 'count': 10}, {'author_id': 2, 'count': 5}]
33
34 ret = (
35 await Book.annotate(count=Count("id"))
36 .filter(count__gt=6)
37 .group_by("author_id")
38 .values("author_id", "count")
39 )
40 print(ret)
41 # >>> [{'author_id': 1, 'count': 10}]
42
43 ret = await Book.annotate(sum=Sum("rating")).group_by("author_id").values("author_id", "sum")
44 print(ret)
45 # >>> [{'author_id': 1, 'sum': 45.0}, {'author_id': 2, 'sum': 10.0}]
46
47 ret = (
48 await Book.annotate(sum=Sum("rating"))
49 .filter(sum__gt=11)
50 .group_by("author_id")
51 .values("author_id", "sum")
52 )
53 print(ret)
54 # >>> [{'author_id': 1, 'sum': 45.0}]
55
56 ret = await Book.annotate(avg=Avg("rating")).group_by("author_id").values("author_id", "avg")
57 print(ret)
58 # >>> [{'author_id': 1, 'avg': 4.5}, {'author_id': 2, 'avg': 2.0}]
59
60 ret = (
61 await Book.annotate(avg=Avg("rating"))
62 .filter(avg__gt=3)
63 .group_by("author_id")
64 .values("author_id", "avg")
65 )
66 print(ret)
67 # >>> [{'author_id': 1, 'avg': 4.5}]
68
69 # and use .values_list()
70 ret = (
71 await Book.annotate(count=Count("id"))
72 .group_by("author_id")
73 .values_list("author_id", "count")
74 )
75 print(ret)
76 # >>> [(1, 10), (2, 5)]

Callers 1

group_by.pyFile · 0.70

Calls 11

CountClass · 0.90
SumClass · 0.90
AvgClass · 0.90
group_byMethod · 0.80
initMethod · 0.45
generate_schemasMethod · 0.45
createMethod · 0.45
valuesMethod · 0.45
annotateMethod · 0.45
filterMethod · 0.45
values_listMethod · 0.45

Tested by

no test coverage detected