|
0
|
| Sreekanth Reddy Balne · 技术社区 · 7 年前 |
|
|
1
1
让我的模型
id | user | notif | ------------------------------------ 1 john doe liked your pic 2 john doe commented on your pic 3 james liked your pic 4 james commented on your pic 5 john doe pinged you 6 john doe showed interest 7 john doe is busy
基本上,我试图通过
上述通知将显示为: 2 notifications from john doe 2 notification from james 3 notofications from john doe 而不是 5 notifications from john doe 2 notification from james 或 1 notifications from john doe 1 notifications from john doe 1 notification from james 1 notification from james 1 notofications from john doe 1 notofications from john doe 1 notofications from john doe 为了实现这一目标,我们正在寻找一本字典,如: {
"john doe": ["notif1", "notif2"],
"james": ["notif1", "notif2"],
"john doe": ["notif1", "notif2", "notif3"] #duplicate key.
}
但是,这是不可能的,因为不允许使用重复的密钥。因此,我将使用元组数组。 [
('john doe', ['notif1', 'notif2']),
('james', ['notif1', 'notif2']),
('john doe', ['notif1', 'notif2', 'notif3']),
]
因此,我们首先对
from itertools import groupby
from operator import attrgetter
qs = Notification.objects.select_related('user').order_by('date_created')
notifs= [(u, list(nf)) for (u, nf) in groupby(qs, attrgetter('user'))]
您已按需要将所有内容整理好
完成! |