Skip to content

Instantly share code, notes, and snippets.

@oubiwann
Created October 14, 2012 01:41
Show Gist options
  • Select an option

  • Save oubiwann/3886932 to your computer and use it in GitHub Desktop.

Select an option

Save oubiwann/3886932 to your computer and use it in GitHub Desktop.
MySQL, Storm, and Relationships
CREATE TABLE parent (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50),
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT NOT NULL AUTO_INCREMENT,
parent_id INT,
name VARCHAR(50),
PRIMARY KEY (id),
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;
from storm.locals import Int, Storm, Reference, ReferenceSet, Unicode
class Parent(Storm):
__storm_table__ = 'parent'
id = Int(primary=True)
name = Unicode()
class Child(Storm):
__storm_table__ = 'child'
id = Int(primary=True)
name = Unicode()
parent_id = Int()
parent = Reference(parent_id, Parent.id)
Parent.children = ReferenceSet(Parent.id, Child.parent_id)
>>> from storm.locals import *
>>> p1 = Parent()
>>> p1.name = u'parent 1'
>>> store.add(p1)
>>> store.flush()
>>> print p1.id
>>> child1 = Child()
>>> child1.name = u'child 1'
>>> store.add(child1)
>>> child1.parent = p1
>>> store.flush()
>>> print child1.id
>>> child2 = Child()
>>> child2.name = u'child 2'
>>> store.add(child2)
>>> p1.children.add(child2)
>>> store.flush()
>>> print child2.id
>>> store.commit()
>>> p1.children.count()
2
>>> for ch in p1.children:
... print "id: %s, name: %s" % (ch.id, ch.name)
...
id: 1, name: child 1
id: 2, name: child 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment