Az wrote:
[SNIP]
>
> The following code maps these classes to respective database tables.
>
>
> # SQLAlchemy database transmutation
> engine = create_engine('sqlite:///:memory:', echo=False)
> metadata = MetaData()
>
> customers_table = Table('customers', metadata,
> Column('uid', Integer, primary_key=True),
> Column('name', String),
> Column('email', String)
> )
>
>
> orders_table = Table('orders', metadata,
> Column('item_id', Integer, primary_key=True),
> Column('item_name', String),
> Column('customer', Integer, ForeignKey('customers.uid'))
> )
>
> metadata.create_all(engine)
> mapper(Customer, customers_table)
> mapper(Orders, orders_table)
>
>
> Now if I do something like:
>
> for order in session.query(Order):
> print order
>
> I can get a list of orders in this form:
>
> Item ID 1001: MX4000 Laser Mouse, has been ordered by customer no.
> 12
>
> =========
>
> What I want to do is find out customer 12's name and email address
> (which is why I used the ForeignKey into the Customer table). How
> would I go about it?
>
> =========
>
You need to add a "relationship" between the two classes. This is
documented at
http://www.sqlalchemy.org/docs/ormtutorial.html#building-a-relationship.
The documentation is using the declarative form. If you want to continue
to use the distinct table definitions followed by mapper definitions, it
would look something like this:
mapper(Orders, orders_table, properties={
'customer_object': relationship(Customer, backref='orders')
})
This will add a 'customer_object' property to the Orders class which
returns the corresponding Customer object. The backref='orders'
parameter means that the Customer object will also get an 'orders'
property which will be a list of all orders owned by the Customer.
You might find it more convenient if your existing 'customer' column was
actually called something like 'customer_id', then you could call your
relationship property 'customer' instead. If you didn't want to rename
the actual column in the database, you can still ask SQLAlchemy to use a
different name for the column, as demonstrated in
http://www.sqlalchemy.org/docs/mappers.html#customizing-column-propertie
s
Hope that helps,
Simon
--
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.