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)
注意的地方:
中间表记录用户对其他用户的关注关系,并记录关注行为发生的时间
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)