~ubuntu-branches/debian/jessie/sqlalchemy/jessie

« back to all changes in this revision

Viewing changes to examples/generic_associations/table_per_related.py

  • Committer: Package Import Robot
  • Author(s): Piotr Ożarowski
  • Date: 2013-10-28 22:29:40 UTC
  • mto: (1.6.9)
  • mto: This revision was merged to the branch mainline in revision 35.
  • Revision ID: package-import@ubuntu.com-20131028222940-t6h277tm5kaiepk4
Tags: upstream-0.8.3
Import upstream version 0.8.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
of parent.   Navigation between parent and "Address" is simple,
10
10
direct, and bidirectional.
11
11
 
 
12
This recipe is the most efficient (speed wise and storage wise)
 
13
and simple of all of them.
 
14
 
 
15
The creation of many related tables may seem at first like an issue
 
16
but there really isn't any - the management and targeting of these tables
 
17
is completely automated.
 
18
 
12
19
"""
13
 
from sqlalchemy.ext.declarative import declarative_base, declared_attr
 
20
from sqlalchemy.ext.declarative import as_declarative, declared_attr
14
21
from sqlalchemy import create_engine, Integer, Column, String, ForeignKey
15
22
from sqlalchemy.orm import Session, relationship
16
23
 
 
24
@as_declarative()
17
25
class Base(object):
18
26
    """Base class which provides automated table name
19
27
    and surrogate primary key column.
23
31
    def __tablename__(cls):
24
32
        return cls.__name__.lower()
25
33
    id = Column(Integer, primary_key=True)
26
 
Base = declarative_base(cls=Base)
27
34
 
28
35
class Address(object):
29
36
    """Define columns that will be present in each
54
61
            "%sAddress" % cls.__name__,
55
62
            (Address, Base,),
56
63
            dict(
57
 
                __tablename__ = "%s_address" %
 
64
                __tablename__="%s_address" %
58
65
                            cls.__tablename__,
59
 
                parent_id = Column(Integer,
60
 
                    ForeignKey("%s.id" % cls.__tablename__)),
61
 
                parent = relationship(cls)
 
66
                parent_id=Column(Integer,
 
67
                            ForeignKey("%s.id" % cls.__tablename__)),
 
68
                parent=relationship(cls)
62
69
            )
63
70
        )
64
71
        return relationship(cls.Address)
104
111
for customer in session.query(Customer):
105
112
    for address in customer.addresses:
106
113
        print address
107
 
        print address.parent
 
 
b'\\ No newline at end of file'
 
114
        print address.parent