In django, how do I sort a model on a field and then get the last item?

后端 未结 5 2038
青春惊慌失措
青春惊慌失措 2021-02-12 11:20

Specifically, I have a model that has a field like this

pub_date = models.DateField(\"date published\")

I want to be able to easily grab the ob

5条回答
  •  甜味超标
    2021-02-12 12:17

    Be careful of using

    Edition.objects.order_by('-pub_date')[0]
    

    as you might be indexing an empty QuerySet. I'm not sure what the correct Pythonic approach is, but the simplest would be to wrap it in an if/else or try/catch:

    try:
        last = Edition.objects.order_by('-pub_date')[0]
    except IndexError:
        # Didn't find anything...
    

    But, as @Harley said, when you're ordering by date, latest() is the djangonic way to do it.

提交回复
热议问题