Reputation: 256
I am trying to return the most recent date from a number of records by a user.
When the user creates a document, the date created is stored in the CreatedDocumentDetails model.
I am unable to return the date of the most recently created document by the user.
I asked this question on SO that is kind of related to the issue.
Here is my model.py code:
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 my views.py code:
def get_latest_created_document_date(user):
??
return latest_created_document_date
I understand I have to pass the date in the filter of the get_latest_created_document_date view of the user, but after searching SO, Google and Django docs, I am still unable to figure this out on my own.
Upvotes: 9
Views: 13222
Reputation:
You'll want to use the order_by
QuerySet filter, like so:
CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first()
Since you are using a date field, you can also use the latest
filter like so:
CreatedDocumentDetails.objects.latest('created_document_timestamp')
As catavaran states in the comments
Note that if there is no records in table then
first()
will returnNone
butlatest()
will raiseDoesNotExist
exception
To just get the datestamp, you can append the field to the end, as both queries will give a single object:
CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first().created_document_timestamp
or
CreatedDocumentDetails.objects.latest('created_document_timestamp').created_document_timestamp
Upvotes: 18