代码之家  ›  专栏  ›  技术社区  ›  Sreekanth Reddy Balne

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

  •  0
  • Sreekanth Reddy Balne  · 技术社区  · 7 年前

    我的应用程序由一个通知模块组成。如果通知是从同一个用户连续到达的,我想显示“来自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
    

    上述通知将显示为:

    2 notifications from john doe
    2 notification from james
    3 notofications from john doe
    

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

    Notification.objects.all().values('user', 'notif_count').group_consecutive_by('user').as(notif_count=Sum())
    

    差不多吧。请帮忙。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sreekanth Reddy Balne    7 年前

    让我的模型 Notification 型号为:

    
    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
    

    基本上,我试图通过 user

    上述通知将显示为:

    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']),
    ]
    

    因此,我们首先对 Notifications 通过 date_created . 然后我们使用 itertools.groupby 为每个用户创建组。

    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'))]
    

    您已按需要将所有内容整理好 notifs .

    完成!