Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

python - Django Get Latest Entry from Database

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 status in status %}

    <tr>
        <td>{{ status.status}}</td>
    </tr>

{% endfor %}

However when I want to retrieve a single object i get an error even when i use:

po = Status.objects.latest('id')

and remove the for loop.

I get:

'Status' object is not iterable

My questions are:

  1. How can I get the latest entry from the database for a given model?
  2. How can I setup my templates tags to allow for just a single record?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have two different questions here:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...