Rockbot
Rockbot

Reputation: 973

How to create DB-Tables on runtime

I want to create certain predefined tables when they are needed - let`s say when the user wants to add a certain functionality to an app.

I understand that MODELS "describe data representations" - so i guess my predefined tables have to go here. I tried this in db.py:

def create_my_table():
    db.define_table('mytesttable',
        Field('mytest', 'text')
            )

What I don't understand is, how to call this method. This is not working:

{{ =A('Create Table', _href = URL('create_my_table')) }}

Upvotes: 0

Views: 168

Answers (1)

Anthony
Anthony

Reputation: 25536

By default, the URL identifies a controller and function within that controller, and the framework runs that function (after executing the model files). You cannot define a function in a model file and then call that function by including its name in a URL. Instead, you should either put the function in a controller, or make a call to your function from a controller.

Also, note that although it is common to define database models in the model files (typically because a given model is often needed in multiple controllers), you can define models anywhere, including in a controller.

Another option is to use the conditional models functionality. For example, you could create a controller action called create_my_table in the default.py controller. You can then create a /models/default/create_my_table.py model file, and that model file will only get executed when the /default/create_my_table action is called (in that case, there is no reason to put the model definition inside a function -- just put it at the top level in that model file). You can also define more sophisticated conditional model execution using response.models_to_run. For more details, see the relevant documentation.

The latter option might be preferable because when using appadmin, all conditional models are automatically run, so you will have access to the conditionally defined models (appadmin will not have access to tables that are only defined in a specific controller).

Upvotes: 1

Related Questions