从Django ORM获取每个用户ID的最新对象

时间:2015-10-06 12:11:24

标签: python django orm group-by aggregate

我有一个包含架构的表: -

           Column       |         Type          |
     --------------------------------------------------------
     id                 | integer               | primary_key
     user_id            | integer               | not null
     total_properties   | integer               | not null
     created_at         | date                  | not null

django模型是: -

class User_Data(models.Model):
    id = models.AutoField(primary_key=True)
    user_id = models.IntegerField()
    total_properties = models.IntegerField()
    created_at = models.DateField(auto_now=True, default=timezone.now)

    class Meta():
        app_label = 'users'

数据类似于: -

      id   | user_id | total_properties | created_at
     --------------------------------------------------------
     1     | 100     | 4                | 2015-10-04
     2     | 101     | 11               | 2015-10-04
     3     | 103     | 7                | 2015-10-04
     4     | 100     | 6                | 2015-10-05
     5     | 103     | 12               | 2015-10-05
     6     | 105     | 1                | 2015-10-05
     7     | 100     | 13               | 2015-10-05
     8     | 106     | 14               | 2015-10-06
     9     | 103     | 40               | 2015-10-06
     10    | 109     | 3                | 2015-10-06

我想为每个created_at获取最新的(即最大total_propertiesuser_id,即以下数据: -

      id   | user_id | total_properties | created_at
     --------------------------------------------------------
     2     | 101     | 11               | 2015-10-04
     6     | 105     | 1                | 2015-10-05
     7     | 100     | 13               | 2015-10-05
     8     | 106     | 14               | 2015-10-06
     9     | 103     | 40               | 2015-10-06
     10    | 109     | 3                | 2015-10-06

请指导如何通过Django Model类实现这一目标

0 个答案:

没有答案