[英]How to count consecutive rows with same value for a column in a database using django?
My App consists of a notification module. 我的应用程序包含一个通知模块。 If the notifications are consecutively arrived from a same user, I would like to show "n notifications from john doe".
如果通知是连续从同一用户到达的,我想显示“来自john doe的n条通知”。
eg: 例如:
5 notifications from john doe 2 notification from james 4 notofications from john doe
How would I count these consecutive rows with same value in a column using django orm? 如何使用django orm在列中对这些具有相同值的连续行进行计数?
Suppose You have a model Notifications
and another model named User
. 假设您有一个模型
Notifications
和另一个名为User
模型。 Then you can group by user_id
然后您可以按
user_id
分组
q=Notifications.objects.filter(user__id=1).values('user__first_name', 'user_id').annotate(c=Count('user__id'))
Just as Shafikur's answer above but I suppose you will have something to denote that the notification is new or hasn't been read. 就像上述Shafikur的回答一样,但我想您将有一些东西表示通知是新的或尚未阅读。 So let's add one more piece to the filter:
因此,让我们再添加一个过滤器:
q=Notification.objects.filter(user__id=1, status='new').values('user__first_name', 'user_id').annotate(c=Count('user__id'))
It's not certain how you track the new notifications in your model, so this is just a rough guess which you should be able to apply to your particular case 不确定如何跟踪模型中的新通知,因此这只是一个粗略的猜测,应该可以将其应用于特定案例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.