简体   繁体   English

在sqlalchemy中基于过滤器创建字典

[英]create dictionary based on filter in sqlalchemy

I am trying to get a data structure like this, based on a many-to-many relationship. 我正在尝试基于多对多关系获得这样的数据结构。

Say for example there is a table with Users and a table with Roles . 假设有一个包含Users的表和一个Roles的表。 A user can have many roles. 用户可以具有许多角色。

user_roles = db.Table(
    'user_roles',
    db.Column('user_id', db.Integer, db.ForeignKey(User.id), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey(Role.id), primary_key=True)
)

What I am trying to get is a data structure like this, where the Role is the key, and the list that follows is all the users of that role, like this 我想要得到的是一个像这样的数据结构,其中Role是关键,而Role的列表是该角色的所有用户,就像这样

{
  'Write_Articles': ['<User Corvid>, <User Crow>'],
  'Delete_Articles': ['<User Corvid>'],
  'Change_Tags': ['<User Crow>', '<User Jeff>'],
  'Kitty_Cat': ['<User Kitty>']
}

How can this be achieved in SQLAlchemy? 如何在SQLAlchemy中实现?

尽早加载关系以避免重复查询,并使用字典理解来操纵结果。

by_name = {g.name: g.users for g in Group.query.options(db.joinedload(Group.users))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM