|
1 | 1 | from sqlalchemy import Table, MetaData, Column, Integer, String, ForeignKey |
2 | | -from sqlalchemy.orm import mapper, relationship, column_property |
3 | | -from sqlalchemy.orm.collections import attribute_mapped_collection, mapped_collection, collection |
| 2 | +from sqlalchemy import event |
| 3 | +from sqlalchemy.orm import mapper, relationship |
4 | 4 |
|
5 | 5 | from domain_model import Order |
6 | 6 |
|
7 | | -metadata = MetaData() |
8 | 7 |
|
| 8 | +metadata = MetaData() |
9 | 9 |
|
10 | 10 | order = Table( |
11 | 11 | 'order', metadata, |
12 | 12 | Column('id', Integer, primary_key=True, autoincrement=True), |
13 | | - # relationship('order_lines', secondary='order_lines') |
14 | 13 | ) |
15 | 14 |
|
16 | 15 | order_lines = Table( |
|
20 | 19 | Column('qty', Integer), |
21 | 20 | ) |
22 | 21 |
|
| 22 | +from dataclasses import dataclass |
23 | 23 |
|
| 24 | +@dataclass |
24 | 25 | class _DummyOrderLine: |
25 | | - pass |
| 26 | + '''dummy type to map order lines, will convert them to and from dicts in events below''' |
| 27 | + order_id: int |
| 28 | + sku: str |
| 29 | + qty: int |
26 | 30 |
|
27 | 31 |
|
28 | 32 | mapper(_DummyOrderLine, order_lines) |
29 | 33 | mapper(Order, order, properties={ |
30 | | - '__lines': relationship(_DummyOrderLine) |
| 34 | + '__lines': relationship(_DummyOrderLine), |
31 | 35 | }) |
32 | 36 |
|
33 | 37 |
|
34 | | -from sqlalchemy import event |
35 | 38 |
|
36 | | -# standard decorator style |
37 | 39 | @event.listens_for(Order, 'load') |
38 | 40 | def custom_load(target, context): |
39 | | - breakpoint() |
40 | 41 | target._lines = {l.sku: l.qty for l in target.__lines} |
| 42 | + target.__lines.clear() |
| 43 | + |
| 44 | +@event.listens_for(Order, 'after_insert') |
| 45 | +def custom_insert(mapper, connection, target): |
| 46 | + for sku, qty in target._lines.items(): |
| 47 | + target.__lines.append(_DummyOrderLine(order_id=target.id, sku=sku, qty=qty)) |
| 48 | + |
| 49 | +@event.listens_for(_DummyOrderLine, 'before_insert') |
| 50 | +def custom_update(mapper, connection, target): |
| 51 | + breakpoint() |
| 52 | + print(target) |
0 commit comments