Sqlalchemy中的模型

时间:2014-06-30 07:36:12

标签: python sqlalchemy flask-sqlalchemy

在每个工作区中我需要添加许多用户,我需要连接到例如5个用户如何处理这个sqlalchemy?

我的模型是这样的:

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(50), unique=True, nullable=False)
    username = db.Column(db.Unicode(20), unique=True, nullable=False, index=True)

    ws = db.relationship('Workspace', backref = 'user', lazy = 'dynamic')


class Workspace(db.Model):
    __tablename__ = 'workspaces'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(50))
    created_on = db.Column(db.DateTime, default=datetime.utcnow)



    users = 

1 个答案:

答案 0 :(得分:1)

您需要多对多关系,以便每个工作区可以拥有多个用户,并且每个用户可以拥有多个工作区。

辅助表用于跟踪哪些用户在哪个工作区中。

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

engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(bind=engine)


class User(Base):
    __tablename__ = 'user'

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


class Workspace(Base):
    __tablename__ = 'workspace'

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

    users = relationship(User, lambda: user_workspace, backref='workspaces')


user_workspace = Table(
    'user_workspace', Base.metadata,
    Column('user_id', Integer, ForeignKey(User.id), primary_key=True),
    Column('workspace_id', Integer, ForeignKey(Workspace.id), primary_key=True)
)


Base.metadata.create_all()

w1 = Workspace(name='Stack Overflow')
w2 = Workspace(name='Meta Stack Overflow')

u1 = User(name='davidism', workspaces=[w1, w2])
u2 = User(name='itmard', workspaces=[w1])
u3 = User(name='john doe')

w3 = Workspace(name='Hyphen Site', users=[u3])

session.add_all([w1, w2, w3])
session.commit()

print [u.name for u in w1.users]  # outputs ['davidism', 'itmard']