0

我的目标是检查是否在特定日期创建了一个对象,以及是否将一个数字添加到列表中。但是,我似乎完全错了。

def week_days_activity(self):

    has = list()

    if ( User_activity.objects.filter(timestamp__gte=datetime.now()-timedelta(days=1))):
       has.append(1)  
    else :
       has.append(0)

    if ( User_activity.objects.filter(timestamp__gte=datetime.now() -timedelta(days=2))):
       has.append(2) 
    else :
       has.append(0)
    if ( User_activity.objects.filter(timestamp__gte=datetime.now() -timedelta(days=3))):
       has.append(3)
    else :
       has.append(0)
    return has

时间戳是:

timestamp = models.DateTimeField(auto_now_add=True, db_index=True)

我一直在搜索stackoverflow,答案似乎围绕着这些方案,但我可能没有得到任何东西。

所以请帮忙。谢谢 :)

4

2 回答 2

1
def week_days_activity(self):

    has = []
    today = datetime.now().today()
    1_day_ago = today - timedelta(days=1)
    2_days_ago = today - timedelta(days=2)
    3_days_ago = today - timedelta(days=3)


    qs = User_activity.objects

    if qs.filter(timestamp__gte = 1_day_ago).count():
        has.append(1)
    else :
       has.append(0)

    if qs.filter(timestamp__range= (2_days_ago, 1_day_ago)).count():
       has.append(2)  
    else :
       has.append(0)

    if qs.filter(timestamp__range= (3_days_ago, 2_days_ago)).count():
       has.append(3)  
    else :
       has.append(0)

    return has

阅读更多关于__range这里

一种更易读的方法(IMO):

has = [0, 0, 0]

today = datetime.now().today()
1_day_ago = today - timedelta(days=1)
2_days_ago = today - timedelta(days=2)
3_days_ago = today - timedelta(days=3)


qs = User_activity.objects
if qs.filter(timestamp__gte = 1_day_ago).count():
    has[0] = 1

if qs.filter(timestamp__range= (2_days_ago, 1_day_ago)).count():
    has[1] = 2

if qs.filter(timestamp__range= (3_days_ago, 2_days_ago)).count():
    has[2] = 3

return has
于 2013-08-22T15:13:39.203 回答
1

为了检查对象是否存在,您可以使用exists运算符:

if ( User_activity.objects.filter(timestamp__gte=datetime.now()-timedelta(days=1)).exists()):
   has.append(1)  
else :
   has.append(0)

或者您可以使用 len() 运算符来确定结果查询的长度。如果给定查询不存在条目,则为零:

qs_today = User_activity.objects.filter(timestamp__gte=datetime.now()-timedelta(days=1)
if len(qs_today) > 0:
   has.append(1)  
else :
   has.append(0)
于 2013-08-22T15:13:57.140 回答