如何检查django中特定日期是否有物体?

时间:2013-08-22 15:00:15

标签: django datetime django-views timedelta

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

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,答案似乎围绕这些方案,但我可能没有得到什么。

所以请帮忙。谢谢:))

2 个答案:

答案 0 :(得分: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 here

稍微可读的方法(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

答案 1 :(得分: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)