简体   繁体   English

如何根据其中一个关键值将此连接查询的结果转换为dict?

[英]How can I turn the results from this joined query into dict based on one of the key values?

Sorry i'm a bit new to all this. 对不起,我对这一切都有点新意。

I'm using psycopg2, python, and postgres. 我正在使用psycopg2,python和postgres。

I have two tables - Users and Events. 我有两个表 - 用户和事件。 I've set up a many-to-many relationship because an event can have many users and users can join many events. 我建立了多对多关系,因为一个事件可以有很多用户,用户可以加入很多事件。 There's an intermediate table called UsersEvents matching User id to Event id. 有一个名为UsersEvents的中间表,将User id与Event id匹配。 I want to get the list of events and users in a dict similar to this: 我想获得类似于此的dict中的事件和用户列表:

[
    {
        event_id: 1,
        event_name : 'event-name',
        joined : [
            {'username' : 'name'},
            {'username' : 'name'},
            {'username' : 'name'}
        ]
    },
    {
        event_id: 2,
        event_name : 'event2-name',
        joined : [
            {'username' : 'name2'},
            {'username' : 'name2'}
        ]
    }
]

I'm running a query like this with psycopg2 to get the list of events and users associated with them: 我正在使用psycopg2运行这样的查询来获取与它们关联的事件和用户列表:

SELECT events.id, event_name, users.username
FROM events
JOIN usersevents on events_id = events.id
JOIN users on usersevents.users_id = users.id;

which returns me back something like this: 这会让我回到这样的事情:

[
    (1, 'event-name', 'name'),
    (1, 'event-name', 'name'), 
    (1, 'event-name', 'name'), 
    (2, 'event2-name', 'name2'),
    (2, 'event2-name', 'name2')
]

So it's great that it pulls back the information I need but now I have to try and figure out how to merge it into the format above. 因此它很好地回收了我需要的信息,但现在我必须尝试找出如何将其合并到上面的格式中。 Is there a better query for what I'm trying to do, or should I just loop through all the results and try merging results with the same event name? 是否有更好的查询我正在尝试做什么,或者我应该循环所有结果并尝试使用相同的事件名称合并结果?

Edit: I understand how to return the results as a dict as pointed out in the comments. 编辑:我理解如何将结果作为dict返回,如评论中所指出的。 I want to take the rows that have duplicate event names and nest the users joining that event into a single dict row for a single event object. 我想获取具有重复事件名称的行,并将加入该事件的用户嵌套到单个事件对象的单个dict行中。

You want to build a data structure for each event by name. 您希望按名称为每个事件构建数据结构。 Create a dict that will map names to event data. 创建一个将名称映射到事件数据的dict。 For each row, either create or update the data for the event. 对于每一行,创建或更新事件的数据。 Finally, the values from the dict is the list of event data. 最后,dict中的值是事件数据列表。

for id, event, user in results:
    event = events.setdefault(id, {'event_id': id, 'event_name': name, 'joined': []})
    event['joined'].append({'username': user})

data = list(events.values())

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

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