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

后端 未结 5 2040
青春惊慌失措
青春惊慌失措 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:14

    This has already been answered, but for more reference, this is what Django Book has to say about Slicing Data on QuerySets:

    Note that negative slicing is not supported:

    >>> Publisher.objects.order_by('name')[-1]
    Traceback (most recent call last):
      ...
    AssertionError: Negative indexing is not supported.
    

    This is easy to get around, though. Just change the order_by() statement, like this:

    >>> Publisher.objects.order_by('-name')[0]
    

    Refer the link for more such details. Hope that helps!

提交回复
热议问题