Question

My aim is to check if there is an object created on the specific day, and if, to add a number to the list. However, I seem to do it totally wrong.

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 is:

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

I've searching around stackoverflow and the answers seem to round around these scheme but I probably don't get something.

So please help. Thanks :)

Was it helpful?

Solution

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

Read more about __range here

A slightly more readable approach (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

OTHER TIPS

In order to check whether an object exist you can use the exists operator:

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

Or you could use the len() operator to determine the length of the resulting query. It's zero if no entries exist for the given query:

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top