I've three tables User, Device and Role. I have created a many-to-many relation b/w User and Device like this;
#Many-to-Many relation between User and Devices
userDevices = db.Table("user_devices",
db.Column("id", db.Integer, primary_key=True),
db.Column("user_id", db.Integer, db.ForeignKey("user.id")),
db.Column("device_id", db.Integer, db.ForeignKey("device.id"))))
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(60), index=True, unique=True)
devices = db.relationship("Device", secondary=userDevices, backref=db.backref('users'), lazy="dynamic")
class Device(db.Model):
__tablename__ = 'device'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60), unique=True)
This works quiet well. I can assign a device d1
to user u1
> d1.users.append(u1)
, and user to device > u1.devices.append(d1)
and db.session.commit()
.
What I want more is to extend the table user_devices
with one more column as role_id
which will be ForeignKey for Role table. So that this table user_devices
will clearly describe a Role
for specific User
on specific Device
. after adding a column role_id
in table user_devices
I described Role
table as;
class Role(db.Model):
__tablename__ = 'role'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60), unique=True)
device = db.relationship("Device", secondary=userDevices, backref=db.backref('roles'), lazy="dynamic")
In this way, how can I assign a Role r1
to User u1
on Device d1
?
here is what I tried:
# First get the device, user and role
deviceRow = db.session.query(Device).filter(Device.name=="d1").first()
userRow = db.session.query(User).filter(User.username=="u1").first()
roleRow = db.session.query(Role).filter(Role.name == "r1").first()
# Then add the user on that device
deviceRow.users.append(userRow)
deviceRow.roles.append(roleRow)
This creates two rows in the table user_devices
Is there any way that we could add two attributes into the table like this ?;
deviceRow.users.append(userRow).roles.append(roleRow)
so that it creates only one row after commit() ?