开发者

Sqlalchemy ORM non-declarative links between tables

I am using SQLAlchemy but not in the declarative manner, I essentially am trying to populate a database using data being fed by a SOAP web service (dynamic classes).

What I am having trouble with is creating the mappings between the different parts of the object, this is being made more difficult by the fact that the tables are on MySQL's MyISAM tables which don't have foreign key support.

import sqlalchemy

dbE = sqlalchemy.creat开发者_C百科e_engine('create string')
dbM = sqlalchemy.MetaData()
dbM.bind = dbE

class Invoice(object):
    pass

class LineItem(object):
    pass

InvoiceTbl = sqlalchemy.Table('Invoices', dbM, autoload = True)
LineItemTbl = sqlalchemy.Table('Invoices_Items', dbM, autoload = True)

LineItemMapper = orm.mapper(InvoiceLineItemTbl, InvoiceLineItemTbl)
InvoiceMapper = orm.mapper(Invoice, InvoiceTbl)

sm = orm.sessionmaker(bind = dbE, autoflush = True, autocommit = False, 
                      expire_on_commit = True)
session = orm.scoped_session(sm)

Using the above I can query for the different parts of an invoice separately with the following, the objects get populated with the columns present in the matching table:

invoiceData = session.query(Invoice).filter(Invoice.InvoiceNumber.like('12345'))
invoiceItems = session.query(LineItem).filter(LineItem.InvoiceNumber.like('12345'))

What I want to do is make the LineItems as part of the Invoice:

orm.mapper(Invoice, InvoiceTbl properties={
    'LineItems' : orm.relation(LineItem),
    })

But this comes back with an error about it doesn't know about the relation between the two objects / tables (understandable given that no foreign keys exist). I've been trying different parameters (primaryjoin, backref, etc) but I have not been successful thus far.

Any help would be appreciated, I understand this may not be the best way to do this but this particular script is data driven and needs to be somewhat dynamic in the event the SOAP service changes.

edit: shahjapan's suggestion of primaryjoin argument helps but I am now getting an error "Could not determine relationship direction for primaryjoin condition" so I assume we are on the right track, just not there yet.


Just give foreign key in the child and it will work authomaticaly.

LineItme

LineItemTbl = sqlalchemy.Table('Invoices_Items', dbM,
    Column(InvoiceNumber, ForeignKey('InvoiceTbl.InvoiceNumber),
    autoload = True)


Try using PrimaryJoin keyword arg of relation API,

orm.mapper(Invoice, InvoiceTbl properties={
    'LineItems' : orm.relation(LineItem,
                  primaryjoin='Table1.id==Table2.refid'),
    })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜