Django Get Latest Entry from Database

前端 未结 5 1420
星月不相逢
星月不相逢 2020-12-11 02:46

I\'ve got 2 questions, but they are related to the same topic.

I know how to retrieve data from a for loop using template tags

{% for st         


        
5条回答
  •  旧时难觅i
    2020-12-11 03:33

    This is because latest returns a single instance rather than a queryset (which is iterable). So:

    1) Latest is not working because it works with Date Fields. Read more at: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest. 'id' is not a valid field to use with the latest filter.

    2) You can't use for template tag with a single instance because it is not iterable.

    To solve your situation, I would specify the ordering = ('id',) field in the Meta class of the model and then do a po = Status.objects.all()[:1] so you will obtain a queryset (which is iterable) with a single object in it. Then you will be able to use the for template tag with your po variable.

    Hope it helps.

提交回复
热议问题