test

import  sqlalchemy
from  sqlalchemy.orm  import  relation, backref, sessionmaker
from  sqlalchemy.ext.declarative  import  declarative_base
from  sqlalchemy  import  Column, Integer, String, ForeignKey
engine 
=  sqlalchemy.create_engine( ' sqlite:///:memory: ' , echo = True)
Base 
=  declarative_base()
session 
=  sessionmaker(bind = engine)()

class  Address(Base):
    
__tablename__   =   ' addresses '
    id 
=  Column(Integer, primary_key = True)
    content 
=  Column(String)
    user_id 
=  Column(Integer, sqlalchemy.ForeignKey( ' users.id ' ))

    
def   __init__ (self, user, content):
        self.user 
=  user
        self.content 
=  content
    
def   __repr__ (self):
        
return   " <Address('%s')> "   %  self.content

    
class  User(Base):
    
__tablename__   =   ' users '
    id 
=  Column(Integer, primary_key = True)
    name 
=  Column(String)
    comment 
=  Column(String)
    addresses 
=  relation( ' Address ' , order_by = ' Address.id ' , backref = ' user ' )
    
def   __init__ (self, name, comment):
        self.name 
=  name
        self.comment 
=  comment
    
def   __repr__ (self):
        
return   " <User('%s', '%s')> "   %  (self.name, self.comment)

    
class  Photo(Base):
    
__tablename__   =   ' photos '
    id 
=  Column(Integer, primary_key = True)
    name 
=  Column(String)
    user_id 
=  Column(Integer, ForeignKey( ' users.id ' ))
    user 
=  relation( ' User ' , backref = backref( ' photos ' ))
    
def   __init__ (self, user, name):
        self.user 
=  user
        self.name 
=  name
    
def   __repr__ (self):
        
return   " <Photo('%s')> "   %  self.name
        
Base.metadata.create_all(bind
= engine)

你可能感兴趣的:(test)