Django return counter on saving date <= last 24 hours

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

I create a test form so that every time the user creates the document, the date and time the document was created will be stored in the CreatedDocumentDetails model. I have not implemented this code yet, I am focused on returning the account within the last 24 hours. I currently inserted values ​​into the CreatedDocumentDetails model manually.

The problem is that I want to count the documents that were created by the user in the last 24 hours. I can return the total score of saved documents, but I don’t know how to write the current date and time field to the if statement in order to return the number 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 corresponding views.py code:

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

I assume that somehow I am now inserting the datetime field into the filter of the get_created_documents code described above.

+5
source share
1 answer

Firstly, your existing code is very flawed. You should never make len in a query that you do not need to iterate over: it retrieves all the data for no reason. Use count() instead:

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

Secondly, since you already have one condition - on the user - it should not be too difficult to add another. You just need to match the date:

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

You can also think about renaming your function and its variables: you actually do not receive the created documents, you count_created_documents them, so count_created_documents or get_created_documents_count will be better names.

+12
source

Source: https://habr.com/ru/post/1210368/


All Articles