我試圖對系統具有用戶,公司,組和角色模型的情況建模。關係如下。SQLAlchemy間表約束
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Unicode(50), unique=True, nullable=False)
first_name = Column(Unicode(50), nullable=False)
last_name = Column(Unicode(50), nullable=False)
company_id = Column(Integer, ForeignKey('companies.id'))
class Company(Base):
__tablename__ = 'companies'
id = Column(Integer, primary_key=True)
name = Column(Unicode(200), unique=True, nullable=False)
users = relationship("User", backref="company")
groups = relationship("Group", backref="company")
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(Unicode(60), nullable=False)
company_id = Column(Integer, ForeignKey('companies.id'), nullable=False)
roles = relationship("Role", backref="group")
class Role(Base):
__tablename__ = 'roles'
id = Column(Integer, primary_key=True)
name = Column(Unicode(60), nullable=False)
group_id = Column(Integer, ForeignKey('groups.id'), nullable=False)
我的問題是,我不知道我怎麼可以強制用戶無法成爲集團成員或角色沒有被擁有該集團的成員公司的約束。
您的示例代碼是否缺少模型中'Users'鏈接到Groups的部分? – van
是的。我不確定最好的方法來做到這一點,所以我把它排除了。我假設向羣組和角色添加users = relationship(「User」,backref =「group | role」)是正確的? –