python - Django Get Latest Entry from Database -
i've got 2 questions, related same topic.
i know how retrieve data for loop
using template tags
{% status in status %} <tr> <td>{{ status.status}}</td> </tr> {% endfor %}
however when want retrieve single object error when use:
po = status.objects.latest('id')
and remove loop.
i get:
'status' object not iterable
my questions are:
- how can latest entry database given model?
- how can setup templates tags allow single record?
you have 2 different questions here:
- how retrieve latest object database.
you can using latest()
queryset operator. reading docs note operator works on date fields, not integers.
status.objects.latest('date_added') # or date_updated
if want off id need order id , select first result. (this work if using incrementing primary keys, not work uuid's or randomly generated hashes).
status.objects.order_by('id')[0]
side note: use date_added / date_updated
way of doing this.
- iterating on single object
a single object cannot iterated over. need use different template. or, need add single object list.
# note [] around query result = [status.object.latest('date_added')]
personally have different views listing single / multiple result. have listview
many result objects , detailview
single objects.
Comments
Post a Comment