Reputation: 1245
I'm considering using sqlite as a application file format and using Pony ORM as a lightweight ORM. So far, all the code examples I've seen place the models a database() object in a separate file.
My question is, when the user makes a new file, how do I instantiate a new database instance for the same database model? (all databases are the same schema)
So one document is linked to one pony-orm database object, another is linked to a separate pony-orm object.
Is this possible in PonyORM? If not, is it possible in any other Python ORM?
Upvotes: 2
Views: 1941
Reputation: 4849
Typically it is better to store all information in a single database. This way you can retrieve all necessary information in a single query.
If you split data across several databases, you cannot mix objects retrieved from different databases and need to work with each database using separate queries (although you can do it in a shared db_session).
If you really want to have multiple databases, you can define entities inside a function:
### file models.py
def define_entities(db):
class Foo(db.Entity):
...
class Bar(db.Entity):
...
def open_database(filename):
db = Database()
define_entities(db)
db.bind('sqlite', filename)
db.generate_mapping(create_tables=True)
return db
### file main.py
db1 = open_database('db1.sqlite')
db2 = open_database('db2.sqlite')
with db_session:
foos = select(foo for foo in db1.Foo if <condition>)[:]
bars = select(bar for bar in db2.Bar if <condition>)[:]
In the example above I wrote a function open_database
which works as a database factory. Each database has its own entity classes, and you can access then as an attributes of db object: db.Foo
, db.Bar
, etc.
Upvotes: 2