[storm] Storm, sqlite, and lists

Christopher Armstrong radix at twistedmatrix.com
Fri Jul 27 19:13:39 BST 2007


On 7/27/07, Jamu Kakar <jamshed.kakar at canonical.com> wrote:
> Below is a script with the previous example implemented.  It produces
> the following output when it runs:

Thanks for the correction, Jamu. I'll point out that this is a great
potential example for AutoReload. See below.

> from storm.locals import create_database, Storm, Store, Int, Unicode
>
>
> class Account(Storm):
>
>     __storm_table__ = "account"
>
>     id = Int(primary=True)
>     owner_id = Int(default=0)
>
>
> class Person(Storm):
>
>     __storm_table__ = "person"
>
>     id = Int(primary=True)
>     name = Unicode()
>
>     def __init__(self, name):
>         self.name = name
>
>
> database = create_database("sqlite:")
> store = Store(database)
>
> store.execute("CREATE TABLE person ("
>               "    id INTEGER PRIMARY KEY,"
>               "    name VARCHAR)",
>               noresult=True)
> store.execute("CREATE TABLE account ("
>               "    id INTEGER PRIMARY KEY,"
>               "    owner_id INTEGER)",
>               noresult=True)
>
> account = store.add(Account())
> account.owner = store.add(Person("Bob"))
> print account.id, account.owner.id

Here, Jamu's example shows the following:

> store.commit()
> print account.id, account.owner.id

But if you want to get the IDs of these objects *without* committing
to the database, you could also do this:

account.id = AutoReload
account.owner.id = AutoReload
print account.id, account.owner.id

Another interesting technique is using default=AutoReload, so that the
ID will automatically be loaded from the database when a value is not
currently available.

class Account(Storm):
    __storm_table__ = "account"

    id = Int(primary=True, default=AutoReload)

account = store.add(Account())
print account.id # should be an actual number

Note that this *doesn't* reload the value from the database on every
attribute access, so don't worry about that. The default= argument
only applies when no value is yet available.

-- 
Christopher Armstrong
International Man of Twistery
http://radix.twistedmatrix.com/
http://twistedmatrix.com/
http://canonical.com/



More information about the storm mailing list