Python 使用django为数据库中的列计算具有相同值的连续行数?

Python 使用django为数据库中的列计算具有相同值的连续行数?,python,django,django-models,django-views,Python,Django,Django Models,Django Views,我的应用程序由一个通知模块组成。如果通知是从同一个用户连续到达的,我想显示“来自john doe的n个通知” 例如: 数据库行如下所示: id | user | notif | ------------------------------------ 1 john doe liked your pic 2 john doe commented on your pic 3 james liked

我的应用程序由一个通知模块组成。如果通知是从同一个用户连续到达的,我想显示“来自john doe的n个通知”

例如:

数据库行如下所示:

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 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 id |用户| notif| ------------------------------------ 约翰·多伊喜欢你的照片 约翰·多伊对你的照片发表了评论 詹姆斯喜欢你的照片 詹姆斯对你的照片发表了评论 约翰·多伊打了你一顿 约翰·多伊表现出了兴趣 约翰·多伊很忙 上述通知将显示为:

2 notifications from john doe 2 notification from james 3 notofications from john doe 2 notifications from john doe 2 notification from james 3 notofications from john doe 2来自john doe的通知 2詹姆斯的通知 约翰·多伊的3个声名 如何使用django orm计算列中具有相同值的连续行数

Notification.objects.all().values('user', 'notif_count').group_consecutive_by('user').as(notif_count=Sum()) Notification.objects.all()值('user','notif_count')。按('user')分组(notif_count=Sum()) 差不多吧。请帮助。

让我的型号
通知
型号:


Class Notification(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='notifications',
        on_delete=models.CASCADE)
    notif = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
数据库行如下所示:

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 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 您已经在
通知中根据需要对所有内容进行了排序


完成了

如果我对你的问题理解正确,你想实现某种通知历史记录,但按日期排序和按用户分组?我不确定,但我认为你不能通过聚合实现。你能做的是,John Doe发了5封通知,James发了2封通知。
@SergeyPugach-yup!是的。@ruddra有可能(不仅仅是聚合),我刚刚找到了解决方案。我很快就会写的。谢谢。@无耻我对你的解决方案很感兴趣,你能把它贴在这里吗?谢谢你的回答。我知道groupby,但希望您已经在SQL中找到了解决方案,这将有助于进一步筛选/排序。 { "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'))]