继续我的last问题。我在3个表之间定义了结构良好的多对多关系。我可以简单地添加一个这样的用户关联
def setUserAssociation(**kwargs):
associations = {}
assoc = UserDevices() #Table object that stores all associations (see my last question)
try:
for table in kwargs:
validTables = ["Site", "User", "Device", "Role"]
if table not in validTables:
raise ValueError("Unknown table `" + table + "` must be " + str(validTables))
associations[table] = db.session.query(eval(k)).filter(eval(table).name==kwargs[table]).first()
if associations[table] is None:
raise ValueError("No " + table + " found with name `" + str(kwargs[table]) + "`")
setattr(assoc, table .lower(), associations[table])
db.session.add(assoc)
db.session.commit()
return SqlResponse(200, "Success")
except Exception as e:
print(e)
return SqlResponse(500, str(e))
最后在站点Anum
上添加用户myHome
并在设备owner
上为其分配角色myPlug
response = setUserAssociation(Site="myHome", User="Anum", Device="myPlug", Role="owner")
足够好!现在说我有一个结构如下的复杂表;
我想将此表构造为Json或Dict对象。调用getUserAssociation时,我可以获取(UserDevice
对象类型的用户关联列表)
def getUserAssociation(userName):
user = db.session.query(User).filter(User.name == userName).first()
return user.user_devices
userAssoc = getUserAssociation("Anum")
for u in userAssoc:
print ("data: ", u.user.name, u.site.name, u.device.name, u.role.name)
这给了我UserDevice对象的列表(每行)。当然,我可以使用上面的数据创建自己的wild方法来创建json(如下所示),但是...还有其他简便的方法吗?也许SqlAlchemy已经提供了一个?
{
"sites": [
{
"site": "myHome",
"devices": [
{
"device": "plug",
"users": [
"{'user': 'John', 'role': 'owner'}",
"{'user': 'Steve', 'role': 'writer'}"
]
},
{
"device": "fan",
"users": [
"{'user': 'Henry', 'role': 'manager'}",
"{'user': 'John', 'role': 'owner'}"
]
}
]
}
]
}