简体   繁体   English

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

[英]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.

相关问题 使用Django计算数据库中列的具有相同值的连续行? - Count consecutive rows with same value for a column in a database using django? 如何检查 pandas 列中接下来的 3 个连续行是否具有相同的值? - How to check if next 3 consecutive rows in pandas column have same value? 如何在一个具有相同值(字符串)的数据框中找到两个连续的行,并在它们之间添加更多行? - how to find two consecutive rows in a dataframe with same value(string) for a column and add more rows between them? 熊猫DataFrame列中特定值的连续行的累积计数 - Cumulative count for consecutive rows of a specific value in a pandas DataFrame column django 按列计数行 - django count rows by column 按列对不同的连续行进行计数 - Count different consecutive rows according group by a column 如何使用熊猫计算列中具有特定字符串值的行数? - How to count number of rows with a specific string value in a column using pandas? 如何检查 5 行的每个值是否连续相同 pandas - How to check each value consecutive same for 5 rows pandas 计算大于当前行值但小于其他列值的连续行数 - Count number of consecutive rows that are greater than current row value but less than the value from other column 使用相同的列值组合连续行 - Combine Consecutive Rows with the Same column values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM