Traditionally when I've written MVC style applications, the model
would contain not only the data representing the objects but also the
data for manipulating the objects. I'm not sure how that same
relation applies to web2py.
If I have a model that defines 4-5 tables, 2 of them are just foreign
key lookups, and creating a new object involves inserting data into 3
of the tables, it seems that I would want a create_object method in my
model file.
So I write something like:
def create_object(owner_id=None, template=None):
# Some sanity checking on the above
new_object = db.objects.insert(template_id=template.id, person_id=owner_id)
widgets = db.template_widget(db.template_widget.thingy_template_id
== template.id).select()
for widget in widgets: db.thingy_widget.insert(widget_id =
widget.id, thingy_id = new_object)
whatchymacallits =
db.template_whatchymacallit(db.template_whatchymacallit.thingy_template_id
== template.id).select()
for whatchymacallit in whatchymacallits:
db.thingy_whatchymacallit.insert(whatchymacallit_id =
whatchymacallit.id, thingy_id = new_object)
return new_object
and place that into my db.py. Now the controller has a function like:
def create():
form = SQLFORM.factory( Field('template',
requires=IS_IN_SET(__get_templates())))
if form.accepts(request.vars, session):
foo = db.create_object(owner_id=auth.auth_id,
template_name=form.vars.template)
response.flash = "Created"
elif form.errors:
response.flash = "Error (hacker)"
Well db is referring to the DAL db not the db.py, from db import
create_object gives a name not found error, so I'm at a loss as to how
to define functions that work upon the model and can be invoked from
one or more controllers. Are there any non-trivial example
applications for web2py? Most of the ones that I have seen assumes
that all data you need in the database can be supplied from a form and
that's not the case I run into over and over again.