I'm newish to SqlAlchemy and for the life of me I can't figure out how
to properly set things up so that lookup tables(objects) are cached
and/or it is easy for new parent objects to associate to their
childing upon initialization. See below for code snippet and sample
problem.
from sqlalchemy import *
#..other imports
metadata = MetaData()
item_types_table = Table('item_types', metadata,
Column('id', Integer, autoincrement=False, primary_key = True),
Column('name', String(50))
)
items_table = Table('items', metadata,
Column('id', Integer, primary_key = True),
Column('item_type_id', Integer, ForeignKey('item_types.id')),
Column('name', String(150))
)
engine = create_engine('mysql://[EMAIL PROTECTED]) #example uri
engine.echo = True
metadata.create_all(engine)
# class definitions
class ItemType(object):
def __init__(self, id, name=None):
self.id = id
self.name = name
class Item(object):
def __init__(self, type_name, name):
self.item_type =
session.query(ItemType).selectfirst(ItemType.c.name==type_name)
# ^^^^ Is there a better way to create this association?
self.name = name
mapper(ItemType, item_types_table)
mapper(Item, item_table, properties = dict(
item_type = relation(ItemType)
)
)
session = create_session(bind_to=engine)
#create item types
t1 = ItemType(0, 'tool')
t2 = ItemType(1, 'widget')
session.save(t1)
session.save(t2)
# ####### Everything works above as expected
item1 =Item('tool', 'sample hammer')
item2 =Item(''tool', 'screwdriver'')
#end of code
####################
So two questions.
1) Upon encountering the last line of code, I see that when I look at
the SQL generated, i see that the select called in the Item __init__
method is sending a query again, instead of using what should in
theory by in the object cache for the exact same query.
2) Basically, I'm trying to get new Item objects to relate to the
correct Item Type via using the name to create the foreignkey (id)
relationship. So the questions is, is the Item Init method setup
right for this, or is there a better way?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---