forked from tortoise/tortoise-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_databases.py
More file actions
92 lines (70 loc) · 2.45 KB
/
Copy pathtwo_databases.py
File metadata and controls
92 lines (70 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
This example demonstrates how you can use Tortoise if you have to
separate databases
Disclaimer: Although it allows to use two databases, you can't
use relations between two databases
Key notes of this example is using db_route for Tortoise init
and explicitly declaring model apps in class Meta
"""
from tortoise import Tortoise, connections, fields, run_async
from tortoise.exceptions import OperationalError
from tortoise.models import Model
class Tournament(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
def __str__(self):
return self.name
class Meta:
app = "tournaments"
class Event(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
tournament_id = fields.IntField()
# Here we make link to events.Team, not models.Team
participants: fields.ManyToManyRelation["Team"] = fields.ManyToManyField(
"events.Team", related_name="events", through="event_team"
)
def __str__(self):
return self.name
class Meta:
app = "events"
class Team(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
event_team: fields.ManyToManyRelation[Event]
def __str__(self):
return self.name
class Meta:
app = "events"
async def run():
await Tortoise.init(
{
"connections": {
"first": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": "example.sqlite3"},
},
"second": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": "example1.sqlite3"},
},
},
"apps": {
"tournaments": {"models": ["__main__"], "default_connection": "first"},
"events": {"models": ["__main__"], "default_connection": "second"},
},
}
)
await Tortoise.generate_schemas()
client = connections.get("first")
second_client = connections.get("second")
tournament = await Tournament.create(name="Tournament")
await Event(name="Event", tournament_id=tournament.id).save()
try:
await client.execute_query('SELECT * FROM "event"')
except OperationalError:
print("Expected it to fail")
results = await second_client.execute_query('SELECT * FROM "event"')
print(results)
if __name__ == "__main__":
run_async(run())