sqlalchemy+postgreSQL(IDLE relationship)
1 >>> from sqlalchemy import create_engine 2 >>> engine = create_engine('sqlite:///:memory:', echo=True) 3 >>> from sqlalchemy.ext.declarative import declarative_base 4 >>> Base = declarative_base() 5 >>> from sqlalchemy import Column, Integer, String 6 >>> from sqlalchemy import ForeignKey 7 >>> from sqlalchemy.orm import relationship, backref 8 >>> class User(Base): 9 __tablename__='users' 10 id = Column(Integer,primary_key=True) 11 name = Column(String) 12 fullname = Column(String) 13 password = Column(String) 14 def __init__(self, name, fullname, password): 15 self.name = name 16 self.fullname = fullname 17 self.password = password 18 def __repr__(self): 19 return "<User('%s','%s','%s')>" % (self.name,self.fullname,self.password) 20 21 22 >>> class Address(Base): 23 __tablename__ = 'addresses' 24 id = Column(Integer, primary_key=True) 25 email_address = Column(String, nullable=False) 26 user_id = Column(Integer,ForeignKey('users.id')) 27 user = relationship("User",backref = backref('addresses',order_by=id)) 28 def __init__(self,email_address): 29 self.email_address = email_address 30 def __repr__(self): 31 return "<Address('%s')>" % self.email_address 32 33 34 >>> Base.metadata.create_all(engine) 35 2013-04-10 21:06:49,775 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users") 36 2013-04-10 21:06:49,851 INFO sqlalchemy.engine.base.Engine () 37 2013-04-10 21:06:49,867 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("addresses") 38 2013-04-10 21:06:49,875 INFO sqlalchemy.engine.base.Engine () 39 2013-04-10 21:06:49,884 INFO sqlalchemy.engine.base.Engine 40 CREATE TABLE users ( 41 id INTEGER NOT NULL, 42 name VARCHAR, 43 fullname VARCHAR, 44 password VARCHAR, 45 PRIMARY KEY (id) 46 ) 47 48 49 2013-04-10 21:06:49,894 INFO sqlalchemy.engine.base.Engine () 50 2013-04-10 21:06:49,901 INFO sqlalchemy.engine.base.Engine COMMIT 51 2013-04-10 21:06:49,907 INFO sqlalchemy.engine.base.Engine 52 CREATE TABLE addresses ( 53 id INTEGER NOT NULL, 54 email_address VARCHAR NOT NULL, 55 user_id INTEGER, 56 PRIMARY KEY (id), 57 FOREIGN KEY(user_id) REFERENCES users (id) 58 ) 59 60 61 2013-04-10 21:06:49,915 INFO sqlalchemy.engine.base.Engine () 62 2013-04-10 21:06:49,921 INFO sqlalchemy.engine.base.Engine COMMIT 63 >>> jack = User('jack', 'Jack Bean', 'giffdd')