Django returns the most recent post date

I am trying to return the most recent date from a number of records by a user.

When the user creates a document, the generated date is stored in the CreatedDocumentDetails model.

I am unable to return the date of the last document created by the user.

I asked this question on SO that pertains to this 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 view.py code:

def get_latest_created_document_date(user):
    ??
    return latest_created_document_date

      

I understand that I need to pass the date in the user's get_latest_created_document_date view filter, but after searching SO, Google and Django docs, I still can't figure it out on my own.

+3


source to share


1 answer


You want to use order_by

a QuerySet filter
like:

CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first()

      

Since you are using a date field, you can also use latest

filter
like so:

CreatedDocumentDetails.objects.latest('created_document_timestamp')

      

How catavaran states in the comments



Note that if there are no records in the table, then it first()

will return None

, but it latest()

will throw an exceptionDoesNotExist

To just get the datestamp, you can add this field to the end, since both requests will provide one object:

CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first().created_document_timestamp 

      

or

CreatedDocumentDetails.objects.latest('created_document_timestamp').created_document_timestamp

      

+6


source







All Articles