Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django return count when date stored <= last 24 hours

Tags:

python

django

I am noob, so this may be a simple question, but it has me stumped.

I am creating a test form so that each time the user creates a document, the date and time the document was created will be stored in the CreatedDocumentDetails model. I have not yet implemented this code yet, I am focusing on returning the count within the last 24 hours. I have inserted the values into the CreatedDocumentDetails model manually for the time being.

The issue is that I want to make a count of the documents that have been created by the user in the last 24 hours. I can return the total count of the users saved documents, but I am unsure how to write the now date & time field into the if statement to return the count of documents created in the last 24 hours.

I have the following model:

class CreatedDocumentDetails(models.Model):
    user = models.ForeignKey(User)
    created_document_timestamp = models.DateTimeField(auto_now_add=True, blank=True)

    def __unicode__(self):
        return unicode(self.user)

Here is the relevant views.py code:

def get_created_documents(user):
    created_documents = len(CreatedDocumentDetails.objects.filter(user=user))
    return created_documents

I am assuming that I somehow insert the now datetime field into the filter of the get_created_documents view code above.

like image 857
user4307426 Avatar asked Jan 04 '15 22:01

user4307426


1 Answers

Firstly, your existing code is very wrong. You should never do len on a queryset that you don't otherwise need to iterate: it fetches all the data, for no reason. Instead, use count():

created_documents = CreatedDocumentDetails.objects.filter(user=user).count()

Secondly, since you already have one condition - on user - it shouldn't be too hard to add another. You just need a date comparison:

date_from = datetime.datetime.now() - datetime.timedelta(days=1)
created_documents = CreatedDocumentDetails.objects.filter(
     user=user, created_document_timestamp__gte=date_from).count()

Also you might consider renaming your function and its variables: you're not actually getting the created documents, you're counting them, so count_created_documents or get_created_documents_count would be better names.

like image 159
Daniel Roseman Avatar answered Nov 18 '22 18:11

Daniel Roseman