S
S
Sergey Nizhny Novgorod2016-01-20 15:21:15
Django
Sergey Nizhny Novgorod, 2016-01-20 15:21:15

How to display the last 3 objects in Django?

Hello.
Task: display on page 3 the latest reviews related to this article.

mentionship = Mention.objects.filter(mentionn_id = step_id)[-3:0] #Не работает

There are no problems with positive ones, but Django does not support negative indexing. How to be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-01-20
@Terras

Mention.objects.filter(mentionn_id=step_id).order_by('-pk')[:3]

Where in order_by you put a field with a minus (in descending order), by which you need to select these very last ones. pk is an alias to the primary key. If you did not change it, this is the ID.
Boyczuk :
If no such ordering is defined for a given QuerySet, calling reverse() on it has no real effect

B
Bojczuk, 2016-01-20
@Bojczuk

mentionship = Mention.objects.filter(mentionn_id = step_id)
mentionship_last3 = mentionship[mentionship.count()-3:]

And from the docs:
https://docs.djangoproject.com/en/dev/ref/models/q...
mentionship_last3 = mentionship.reverse()[:3]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question