选择5个最新的DISTINCT行

时间:2012-10-01 23:13:22

标签: python django

我的模型看起来像这样:

class UserRating(models.Model):

    RATING_CATEGORIES = (
        1: 'Bad',
        2: 'Boring',
        3: 'Average',
        4: 'Good',
        5: 'Great'
    )

    for_user = models.ForeignKey(User, related_name='for_user')
    by_user = models.ForeignKey(User, related_name='by_user')
    rating_category = models.IntegerField(choices=RATING_CATEGORIES)
    points = models.IntegerField(_('Points'), default=0)
    created = models.DateTimeField(_('Created'))

现在,我想根据rating_category评分为by_user的{​​{1}}选择5个最新行。

我做过这样的事情:

for_user

但它会根据entries = UserRating.objects.values('rating_category').filter( for_user=for_user, by_user=by_user).order_by('-created')[:5] 返回重复的行。

假设我有以下MySQL表条目:

rating_category

所需的输出是: id for_user by_user rating_category points created 1 1 1 1 100 2012-09-28 00:19:00 2 1 1 2 100 2012-09-28 00:18:00 3 1 1 4 100 2012-09-28 00:17:00 4 1 1 4 0 2012-09-28 00:16:00 5 1 1 3 100 2012-09-28 00:15:00 6 1 1 5 0 2012-09-27 00:19:00 7 1 1 2 0 2012-09-26 00:18:00

根据rowid-1, rowid-2, rowid-3, rowid-5, rowid-6日期,仅基于rating_categorylatest的不同行。

1 个答案:

答案 0 :(得分:2)

DISTINCT在这里是一个红鲱鱼。您要做的是按rating_category对记录进行分组,然后为每个组选择具有最新创建日期的记录。所以你想要一个像这样的查询:

from django.db.models import Max
entries = (UserRating.objects.filter(for_user = for_user, by_user = by_user)
           .values('rating_category')
           .annotate(last_created = Max('created'))
           .order_by('-last_created'))[:5]

这将返回包含键rating_categorylast_created的词典。