SQLAlchemy学习笔记(外键,关联) 3

下面是数据库关联

  1. 一对多(一个User可以有多个Address)
    ①建立外键 一对多关系
    class User(Base):
    	__tablename__ = "users"
    	id = Column(Integer, Sequence("user_id_seq"), primary_key=True)
            # ...
    	addresses = relationship("Address", backref="user", order_by="Address.id") # User中有addresses字段
            # ...
    
    class Address(Base):
        # ...
        id = Column(Integer, primary_key=True)
        user_id = Column(Integer, ForeignKey("users.id")) # Address表的外键是User表的主键 多个Address属于一个User(多对一)
        # ...
    下面是完整代码
    # -*- coding: utf-8 -*-
    
    from sqlalchemy import Column, Sequence, String, Integer, ForeignKey
    from sqlalchemy import create_engine # 导入创建连接驱动
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.orm import relationship, backref
    
    engine = create_engine("mysql://root:[email protected]/test", echo=True) # 这个url可以用urlparse解析, 其中echo=True表示执行时显示sql语句
    Base = declarative_base() # 生成了declarative基类, 以后的model继承此类
    
    class User(Base):
    	__tablename__ = "users"
    	id = Column(Integer, Sequence("user_id_seq"), primary_key=True) # Sequence表示id自增长, 主键
    	name = Column(String(50))
    	fullname = Column(String(50))
    	password = Column(String(12))
    	addresses = relationship("Address", backref="user", order_by="Address.id")
    
    	def __init__(self, name, fullname, password):
    		self.name = name
    		self.fullname = fullname
    		self.password = password
    
    	def __repr__(self):
    		return "<User('%s', '%s', '%s')>" % (self.name, self.fullname, self.password)
    
    class Address(Base):
        __tablename__ = "addresses"
        id = Column(Integer, primary_key=True)
        email_address = Column(String(50), nullable=False)
        user_id = Column(Integer, ForeignKey("users.id")) # Address表的外键是User表的主键 多个Address属于一个User(多对一)
        user = relationship("User", backref=backref("addresses", order_by=id))
        
        def __init__(self, email_address):
            self.email_address = email_address
            
        def __repr__(self):
            return "<Address('%s')>" % self.email_address  Base.metadata.create_all(engine)
    

    ②使用

    Session = sessionmaker(bind=engine) # 创建一个Session类
    session = Session() # 生成一个Session实例
                             
    zhangsan = User("zs", "zhangsan", "abcdef")
    zhangsan.addresses = [
            Address(email_address="[email protected]"),
            Address(email_address="[email protected]"),
            ]
    
    session.add(zhangsan)
    session.commit()

    ③下面对应的sql语句

    CREATE TABLE users (
    	id INTEGER NOT NULL AUTO_INCREMENT, 
    	name VARCHAR(50), 
    	fullname VARCHAR(50), 
    	password VARCHAR(12), 
    	PRIMARY KEY (id)
    )
    
    CREATE TABLE addresses (
    	id INTEGER NOT NULL AUTO_INCREMENT, 
    	email_address VARCHAR(50) NOT NULL, 
    	user_id INTEGER, 
    	PRIMARY KEY (id), 
    	FOREIGN KEY(user_id) REFERENCES users (id)
    )








你可能感兴趣的:(sqlalchemy)