0

我的模型如下所示:

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

现在我想根据评分选择 5 个最新rating_category的行。by_userfor_user

我做了这样的事情:

entries = UserRating.objects.values('rating_category').filter(
        for_user=for_user,
        by_user=by_user).order_by('-created')[:5]

但它会返回基于rating_category.

假设我有以下 MySQL 表条目:

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根据created日期的不同行。

4

1 回答 1

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_category这将返回带有键和的字典last_created

于 2012-10-02T09:58:53.433 回答