0

我有一个模型名称 Ratings ,其中有一个时间戳。我想将用户限制为每天仅 3 个评分。如何计算特定用户在过去 24 小时内的评分?

class Ratings(models.Model):   
    user = models.ForeignKey(User)
    book = models.ForeignKey('Books')
    rating = models.IntegerField(max_length=150)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_checkedin_rating = models.BooleanField()

编辑*为了更清楚,我想查找特定用户在 24 小时内的评分计数。因此,假设从 5/13 12AM 到 5/14 12AM,计算收视率。

4

1 回答 1

1
import datetime

today = datetime.date.today()
end_time = datetime.datetime.fromordinal(today.toordinal()) // today at 12:00am or 00:00
start_time = end_time -  datetime.timedelta(days=1) yesterday at 12:00am

count = Ratings.objects.filter(
    user=some_user,
    timestamp__gte=start_time,
    timestamp__lte=end_time
).count()
于 2012-05-15T02:25:37.683 回答