1.5.3.1 Full Code Listing

###
1.5.3.1 Full Code Listing

Here is a complete code listing so that you can experiment:

    #!/usr/bin/env python

    import sys; sys.path.append('../../../') # show python where the modules are

    import web.database, web.database.object
    connection = web.database.connect(
        adapter="snakesql",
        database="database-object-multiple",
        autoCreate = 1,
    )
    cursor = connection.cursor()

    person = web.database.object.Table("Person")
    person.addColumn(web.database.object.String(name="firstName"))
    person.addColumn(web.database.object.String(name="surname"))
    person.addMultiple(name="addresses", foreignTable="Address")

    address = web.database.object.Table("Address")
    address.addColumn(web.database.object.String(name="firstLine"))
    address.addColumn(web.database.object.String(name="postcode"))
    address.addSingle(name="person", foreignTable="Person")

    database = web.database.object.Database()
    database.addTable(person)
    database.addTable(address)
    database.init(cursor)

    if not database.tablesExist():
        database.createTables()
        print "Created Table"
    else:
        raise Exception('Tables not created')
    john = database['Person'].insert(firstName='John', surname='Smith')
    print john['surname']
    print john['addresses']

    database['Address'].insert(person=john, firstLine='12 Friendly Place', postcode='OX4 1AB')
    database['Address'].insert(person=john, firstLine='3a Crazy Gardens', postcode='OX1 2ZX')

    for address in john['addresses'].values():
        print address['firstLine']

    connection.close() # Close the connection without saving changes

The output is:

    Created Table
    Smith
    {}
    12 Friendly Place
    3a Crazy Gardens

You will need to delete the database file object-multiple.db each time you run the cose so that it can be recreated each time.