Return 列和相关列表
Return columns and relative list
我有两个 table:
位置
table名称 = "地点"
- loc_id: 整数
- 姓名:海峡
- 用户 = 关系(...)
用户
table名称 = "用户"
- user_id: 整数
- 用户名:str
- 地点 = 关系(...)
并关联 table:
user_location = Table(
"user_location",
Base.metadata,
sa.Column("user_id", sa.Integer),
sa.Column("loc_id", sa.Integer),
sa.PrimaryKeyConstraint("loc_id", "user_id"),
sa.ForeignKeyConstraint(("loc_id",), ("location.loc_id",)),
sa.ForeignKeyConstraint(("user_id",), ("user.user_id",)),
)
我要return下一个:
[
{
"username": "user_1",
"locations": [... list of users loc_id ...]
},
{
"username": "user_2",
"locations": [... list of users loc_id ...]
},
...
]
我试过类似的方法:
db.query(User.username, User.locations).all()
但它不起作用
关系可以作为您正在查询的任何模型的属性访问(前提是您的关系设置正确)。您的问题应该类似于:
users = db.query(User).all()
# Alternatively you can filter on a specific user by using the following query:
users = db.query(User).filter(User.name == 'whatever name you want').all()
# Mimicking the actual list with dicts like you have above
user_list = list()
for u in users:
user_list.append({'username': u.name, 'locations': [l.loc_id for l in u.locations})
如果我上面的内容不起作用,我会要求提供有关这些关系属性的更多详细信息,因为它们可能配置错误。
我有两个 table:
位置 table名称 = "地点"
- loc_id: 整数
- 姓名:海峡
- 用户 = 关系(...)
用户 table名称 = "用户"
- user_id: 整数
- 用户名:str
- 地点 = 关系(...)
并关联 table:
user_location = Table(
"user_location",
Base.metadata,
sa.Column("user_id", sa.Integer),
sa.Column("loc_id", sa.Integer),
sa.PrimaryKeyConstraint("loc_id", "user_id"),
sa.ForeignKeyConstraint(("loc_id",), ("location.loc_id",)),
sa.ForeignKeyConstraint(("user_id",), ("user.user_id",)),
)
我要return下一个:
[
{
"username": "user_1",
"locations": [... list of users loc_id ...]
},
{
"username": "user_2",
"locations": [... list of users loc_id ...]
},
...
]
我试过类似的方法:
db.query(User.username, User.locations).all()
但它不起作用
关系可以作为您正在查询的任何模型的属性访问(前提是您的关系设置正确)。您的问题应该类似于:
users = db.query(User).all()
# Alternatively you can filter on a specific user by using the following query:
users = db.query(User).filter(User.name == 'whatever name you want').all()
# Mimicking the actual list with dicts like you have above
user_list = list()
for u in users:
user_list.append({'username': u.name, 'locations': [l.loc_id for l in u.locations})
如果我上面的内容不起作用,我会要求提供有关这些关系属性的更多详细信息,因为它们可能配置错误。