Reputation: 23
I want to display the last 3 created objects onto my website. I have no clue what to do. I just need to know how to order the model according to created date. And, access the 1st, 2nd and 3rd item of the ordered set.
I'm pretty sure this doesn't work. This is from views.py
latest = Upcoming_Events.objects.all().order_by('date')[:3]
event1 = latest.get(pk=1)
event2 = latest.get(pk=2)
event3 = latest.get(pk=3)
I keep getting
'Cannot filter a query once a slice has been taken'
Upvotes: 1
Views: 122
Reputation: 6404
You can make ORM like this
latest = Upcoming_Events.objects.all().order_by('-date')[:3]
Then in template
{% for event in latest %}
{{ event.date }}
{% endfor %}
Update: As per comment try this
event1 = latest[0]
event2 = latest[1]
event3 = latest[2]
Upvotes: 3
Reputation: 774
make a descending order on pk(id)
latest = Upcoming_Events.objects.all().values().order_by('-id')[:3]
then:
event1 = latest[0]
UPDATE
Notice that you have to use .values()
.
If you do not use it the SQL Query will not contain LIMIT 3
Upvotes: 1