【SQLAlchemy】第7节:模型类自关联一对多、多对多

【SQLAlchemy】第7节:模型类自关联一对多、多对多

    • 1. 自关联一对多的实现
    • 2. 自关联多对多的实现

1. 自关联一对多的实现

User类中:

  • name 用户名
  • introducer_id 这个用户注册时候填写的介绍人,指向User类
from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer,ForeignKey
from sqlalchemy.orm import relationship,backref
from sqlalchemy.ext.declarative import declarative_base


engine = create_engine(
    'mysql+pymysql://root:12345@localhost:3306/tor1',
    echo=False
)

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer,primary_key=True)
    name = Column(String(16),nullable=False)

    introducer_id = Column(Integer,ForeignKey('user.id'))
    introducer = relationship(
        'User',
        foreign_keys = [introducer_id,],
        remote_side = [id],
        backref = backref('introduced_users',lazy='dynamic'),
    )

Base.metadata.create_all(engine)

注意的地方:

  • 维护1对多自关联关系的时候(relationship),必须加入remote_side = [id],表示introducer使用introducer_id指向User类中的id字段

2. 自关联多对多的实现

中间表记录用户对其他用户的关注关系,并记录关注行为发生的时间

from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer,ForeignKey,DateTime,Table
from sqlalchemy.orm import relationship,backref
from sqlalchemy.ext.declarative import declarative_base
import datetime


engine = create_engine(
    'mysql+pymysql://root:12345@localhost:3306/tor1',
    echo=False
)

Base = declarative_base()

user_user_fans = Table(
    'user_user_fans',
    Base.metadata,
    Column('id',Integer,primary_key=True,autoincrement=True),
    Column('user_id',Integer,ForeignKey('user.id')),
    Column('fan_id',Integer,ForeignKey('user.id')),
    Column('createDatetime',DateTime,default=datetime.datetime.now())
)

class User(Base):

    __tablename__ = 'user'

    id = Column(Integer,primary_key=True)
    name = Column(String(16),nullable=False)

    fans = relationship(
        'User',
        secondary = user_user_fans,
        primaryjoin = (user_user_fans.c.user_id == id),
        secondaryjoin = (user_user_fans.c.fan_id == id),
        backref = backref('faned_users',lazy='dynamic'),
        lazy = 'dynamic',
    )

Base.metadata.create_all(engine)

定义说明:
【SQLAlchemy】第7节:模型类自关联一对多、多对多_第1张图片

你可能感兴趣的:(【SQLAlchemy】第7节:模型类自关联一对多、多对多)