从Python中筛选的结果中获取今天日期的操作计数

2024-10-02 00:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户一天可以做很多次的动作。我想知道用户已经做了多少次这样的操作,但只针对今天的日期。这是我目前解决这个问题的方法,但是有没有更简单的方法?我觉得我应该能把这个放在一条线上。:)

today_slaps = 0
slaps = Slap.objects.filter(from_user=request.user.id)
for slap in slaps:
    if slap.date.date() == datetime.now().date():
        today_slaps += 1

我要找的逻辑是:

^{pr2}$

但这显然抛出了一个错误,即关键字不能是表达式。抱歉,如果这是一个基本的问题,但想法呢?在


Tags: 方法用户fromidfortodaydateobjects
2条回答

多亏了Yuji(下图),我们得出了这个答案:

slap_count = Slap.objects.filter(from_user=request.user.id, date__gte=datetime.today().date()).count()
slap_count = Slap.objects.filter(from_user=request.user, \ 
                      date__gte=datetime.date.today()).count()

# specifically setting datetimefield=datetime.date.today() won't work
# gte = will work for datetimefield vs datetime object starting at that date
# it's also assumed there will never be a slap from the future. 

生成以下SQL:

^{pr2}$

所以可以肯定的说,你只会得到今天的耳光,除非你有来自未来的耳光。如果您这样做,我会显式地设置everydate__day, date__year, date__month。在

相关问题 更多 >

    热门问题