10

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.

1 Answer 1

32

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Daniel, thanks for the advice and the date comparison code. This is very helpful. In my views.py I have added the from datetime import datetime, timedelta - but I am getting the error: type object 'datetime.datetime' has no attribute 'datetime'. Is this error to do with the import datetime?
@user4307426 Use either import datetime, or datetime.now() - timedelta(days=1). The datetime module contains a datetime object, so this can cause some confusion at first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.