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:

  1. how can latest entry database given model?
  2. how can setup templates tags allow single record?

you have 2 different questions here:

  1. 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.

  1. 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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -