models
dir.This directory is particularly important due to some characteristics:
models
directory files ares executed in alphabetical order;- Your application's database tables definitions stay in it;
- Objects defined by these files become available on your app's global scope. They can be accessed by controllers and views.
Some newbies have dificulties with that, and tend to think this is strange. I did it, until I concluded this is the most intuitive way to things work. It gives me freedom to organize my app.
However, to avoid some mistakes this way can bring to your app, we need to adopt a clear and fool proof convetion to name
models
files. I use this simple and efficient structure:
models/0_db.py
models/1_menu.py
models/5_models.py
models/5_validators.py
db.py
file to 0_db.py
. So, I guarantee all basic definitions are executed before anything else. The DAL object, who provides all data access funcionalities, is created in this script.I also rename
menu.py
to 1_menu.py
forcing all menu definitions to be executed after DAL object instantiation.With these modified names, I'm sure that all the code I'll develop will be executed after the scaffolding app web2py generated to me.
From that point I write
models/5_models.py
with my table definitions. Nothing but db.define_table()
commands.Validators are written in
models/5_validators.py
. But, why separated from model definitions? First, because web2py recommends you don't mix validators with db.define_table()
. Second, because at this point I'm certain all tables are already created and all cross references between them will work with no need to adjust definition sequences. Sometimes it messes my scripts.When I have many tables, I can separate them in various scripts, i.e,
5_models_accounts.py
, 5_models_finances.py
, etc. And, the same way, their validators.Here, your creativity can fly, but remeber some principles:
Explicit is better than implicit.
Simple is better than complex.
Flat is better than nested.
Readabilty counts.
In the face of ambiguity, refuse the temptation to guess.