用 flask-sqlalchemy 创建了三张表
class userGroup(db.Model):
__tablename__ = 'user_group'
id = db.Column(SMALLINT(unsigned=True), primary_key=True)
group_name = db.Column(db.String(64), unique=True, nullable=False,index=True)
display_name = db.Column(db.String(64))
db_instance_lists = db.relationship('databaseInstance',
cascade='all',
secondary=DBMap,
backref=db.backref('user_group',lazy='dynamic'),
lazy='dynamic'
)
def __repr__(self):
return '<User_group %r>' % self.group_name
class databaseInstance(db.Model):
__tablename__='database_instance'
id = db.Column(SMALLINT(unsigned=True),primary_key=True)
db_instance_name = db.Column(db.String(40),nullable=False)
db_instance_display_name = db.Column(db.String(64))
db_port = db.Column(SMALLINT(unsigned=True),nullable=False)
db_instance_type = db.Column(db.Enum("sqlserver","oracle","mysql"),nullable=False)
i = db.Index("db_instance_name_port",db_instance_name,db_port,unique=True)
db_user_lists = db.relationship('databaseUser',
cascade='all',
secondary=DBMap,
backref=db.backref('db_instance',lazy='dynamic'),
lazy='dynamic'
)
def __repr__(self):
return "<db_instance %r>" % self.db_instance_name
class databaseUser(db.Model):
__tablename__='database_user'
id = db.Column(SMALLINT(unsigned=True),primary_key=True)
db_user_name = db.Column(db.String(40),nullable=False)
db_user_display_name = db.Column(db.String(64))
db_user_password_encypt = db.Column(db.String(64), nullable=False)
def __repr__(self):
return "<dbuser %r>" % self.dbuser_name
现在想再创建一张表,把这三张表关联起来
类似这样:
user_group_id | database_instance_id | database_user_id |
---|---|---|
1 | 1 | 1 |
用的是 Table:
DBMap=db.Table('db_map',
db.Column('user_group_id',SMALLINT(unsigned=True), db.ForeignKey('user_group.id')),
db.Column('db_instance_id',SMALLINT(unsigned=True), db.ForeignKey('db_instance.id')),
db.Column('db_user_id',SMALLINT(unsigned=True), db.ForeignKey('db_user.id'))
)
然后在 user_group 和 database_instance 上加了 relationship ,但是 db_map 添加行的时候
我用
user_group.db_instance_lists.append(db_instance.db_user_list.append(dbuser))
方法就会变成:
user_group_id | database_instance_id | database_user_id |
---|---|---|
2 | 2 | |
2 | 3 |
类似这样
我知道问题出在哪, user_group 对应 db_instance 是一个 list , db_instance 对应的 db_user 也是一个 list , user_group 和 db_user 要通过 db_instance 对应起来。只是现在我不知道三张表关联的话这个 relationship 要怎么写。
求赐教!