| 1 | from elixir import * |
|---|
| 2 | metadata.bind='sqlite:///' |
|---|
| 3 | |
|---|
| 4 | from sqlalchemy.orm.collections import attribute_mapped_collection |
|---|
| 5 | |
|---|
| 6 | class Item(Entity): |
|---|
| 7 | name = Field(String(128)) |
|---|
| 8 | attributes = OneToMany('Attribute', collection_class=attribute_mapped_collection('name')) |
|---|
| 9 | |
|---|
| 10 | def __repr__(self): |
|---|
| 11 | return 'Item(%s)' % (self.name,) |
|---|
| 12 | |
|---|
| 13 | class Attribute(Entity): |
|---|
| 14 | item = ManyToOne('Item', primary_key=True) |
|---|
| 15 | name = Field(String(128), primary_key=True) |
|---|
| 16 | |
|---|
| 17 | def __repr__(self): |
|---|
| 18 | return 'Attribute(%s, %s)' % (self.name, self.value) |
|---|
| 19 | |
|---|
| 20 | setup_all(True) |
|---|
| 21 | |
|---|
| 22 | item1 = Item(name='item1') |
|---|
| 23 | # uncomment this to fail at the first assertion |
|---|
| 24 | #print item1.attributes |
|---|
| 25 | attr1 = Attribute(name='attr1key', value='attr1value', item=item1) |
|---|
| 26 | print item1.attributes |
|---|
| 27 | assert not None in item1.attributes |
|---|
| 28 | assert 'attr1key' in item1.attributes |
|---|
| 29 | assert attr1 in session.new |
|---|
| 30 | |
|---|
| 31 | # this works fine, even after accessing item1.attributes |
|---|
| 32 | attr2 = Attribute(name='attr2key', value='attr2value') |
|---|
| 33 | # because we've explicitly deferred setting the .item until |
|---|
| 34 | # after the attribute is instantiated. |
|---|
| 35 | attr2.item = item1 |
|---|
| 36 | print item1.attributes |
|---|
| 37 | assert not None in item1.attributes |
|---|
| 38 | assert 'attr2key' in item1.attributes |
|---|
| 39 | assert attr2 in session.new |
|---|
| 40 | |
|---|
| 41 | # anytime after we've accessed item1.attributes, if we try to initialize |
|---|
| 42 | # an attribute for that item, the attribute will not be correctly |
|---|
| 43 | # associated and will be lost from the session. |
|---|
| 44 | attr3 = Attribute(name='attr3key', value='attr3value', item=item1) |
|---|
| 45 | print item1.attributes |
|---|
| 46 | assert not None in item1.attributes |
|---|
| 47 | assert 'attr3key' in item1.attributes |
|---|
| 48 | assert attr3 in session.new |
|---|