You have two different questions here:
- How do I retrieve the latest object from the database.
You can do this using the latest()
queryset operator. By reading the docs you will note that this operator works on date fields, not integers.
Status.objects.latest('date_added') # or date_updated
If you want to do this off the ID you will need to order by ID and select the first result. (this will only work if you are using incrementing primary keys, it will not work with UUID's or randomly generated hashes).
Status.objects.order_by('id')[0]
Side note: I would personally use the date_added / date_updated
way of doing this.
- Iterating over a single object
A single object cannot be iterated over. For this you will need to use a different template. Or, you will need to add the single object into a list.
# note the [] around the query
result = [Status.object.latest('date_added')]
Personally I have a different views for listing single / multiple result. I have a ListView
for many result objects and a DetailView
for single objects.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…