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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With