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

后端 未结 5 2044
青春惊慌失措
青春惊慌失措 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条回答
  •  -上瘾入骨i
    2021-02-12 12:08

    obj = Edition.objects.latest('pub_date')
    

    You can also simplify things by putting get_latest_by in the model's Meta, then you'll be able to do

    obj = Edition.objects.latest()
    

    See the docs for more info. You'll probably also want to set the ordering Meta option.

提交回复
热议问题