rdbisme
rdbisme

Reputation: 877

How do I use association proxy with classical mapping?

I read around the internet on examples using association proxies, but all of them I found were written with a declarative style of mapping.

Can I use them in a classical mapping? The reason why is that I'm implementing database persistence to an already existent class hierarchy and I'd like keep the db-related code in a separate file.

As an example, let's assume a model where we have an Item and an Order objects. We build a many-to-many relationship with an extra field in the association table that is, as an example, the price paid for the item:

item = Table('item', metadata, 
             Column('id', Integer, primary_key=True), 
             Column('name', String), 
             Column('quantity', Integer)
             )

order = Order('order', metadata,
              Column('id', Integer, primary_key=True), 
              Column('customer_id', Integer, ForeignKey('user.id'))
             )

order_item = Table('order_item', metadata,
                   Column('order_id', Integer, ForeignKey('order.id')), 
                   Column('item_id', Integer, ForeignKey('item.id')), 
                   Column('price', Float)
                  )

# Mapping of Tables to non-orm objects

Let's assume I'd like to access in a nice way the items of an order as explained in the docs for a User-Keyword example . In the declarative way an attribute is added to the class that is an association proxy:

# ... Class definition ...
items = association_proxy('order_items', 'items')

How do I do this in a classical mapping style?

Upvotes: 1

Views: 742

Answers (1)

univerio
univerio

Reputation: 20548

From the documentation:

The AssociationProxy object produced by the association_proxy() function is an instance of a Python descriptor. It is always declared with the user-defined class being mapped, regardless of whether Declarative or classical mappings via the mapper() function are used.

So, just define it on the class:

class Order(object):
    ...
    items = association_proxy('order_items', 'items')

Upvotes: 2

Related Questions