Best way to organize folders containing SQLAlchemy models

I use SQLAlchemy at work, and it really works well. Now I'm thinking about best practices.

I am currently creating a module that contains all the SQLA materials:

my_model |__ __init__.py |__ _config.py <<<<< contains LOGIN, HOST, and a MetaData instance |__ table1.py <<<<< contains the class, the model and the mapper for table1 |__ table2.py <<<<< contains the class, the model and the mapper for table2 [...] 

Now I really don't know if this is the best for this. I would like to load the fine-grained classes and be sure to create one connection with only db etc.

Here all classes are separated, but all are import _config and I wonder if this is good.

What more, I would like to be able to create subclasses of model classes that can be saved independently without messing with the cartographer every time. How can i do this?

For now, I just put them in the same file, and I need to create another mapper, but the first cartographer is still called every time. The same thing would happen if I had to import the parent class, because when I try to import the cartger starts. If I do not use the class to access data, do not overheat it every time?

I would also like to avoid using Elixir.

+6
python orm sqlalchemy
source share
1 answer

Personally, I like to maintain the database logic / ORM from the model classes. This makes testing them easier. Usually I have something like types.py that defines the types used in my application, but regardless of the database.

Then usually there is db.py or something similar, which has the Session class, and the rest of the code is needed to configure the database, including all the mappers, etc.

None of the other modules, except those that perform database operations, should import the db module, and the presence of the database is completely hidden from most application classes.

As far as I know, you cannot easily subclass without changing the mapping. SQLAlchemy will not be able to find out which subclass to get from the database when executing the query, and you should be able to specify the subclass when you save the data anyway.

I really didn’t see any problems with calling all mappers directly from the main db module, so I don’t think that initializing them all the time really is troubling if you do not really identify this as a bottleneck, In my experience, another processing - a much larger factor than negligible overhead.

+3
source share

All Articles