137๐
You can pass your queryset to reversed:
last_ten = Messages.objects.filter(since=since).order_by('-id')[:10]
last_ten_in_ascending_order = reversed(last_ten)
78๐
Or use [::-1]
instead of reversed
:
last_ten = Messages.objects.filter(since=since).order_by('-id')[:10][::-1]
@ron_g:
Above solution uses list comprehension twice (first to slice to 10, then to reverse). You can do it as one operation, itโs 9x faster.
last_ten = Messages.objects.filter(since=since).order_by('-id')[:10:-1]
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-Django rest framework serializing many to many field
- [Django]-ImproperlyConfiguredError about app_name when using namespace in include()
34๐
If you want last X records sorted in descending order by id , Then I donโt think you need since filter
last_ten = Messages.objects.all().order_by('-id')[:10]
Using -id will sort in descending order.
Hope this was helpful !!
- [Django]-Django self-referential foreign key
- [Django]-CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
- [Django]-Use Python standard logging in Celery
4๐
I wanted to retrieve the last 25 messages and solved this problem in the following way
#models.py
class Meta:
ordering = ['created']
#views.py
message1 = []
for message in pm_messages.objects.filter(room=room_name).reverse()[0:25]:
message1.append(message)
messagess = message1.reverse()
- [Django]-Django gives Bad Request (400) when DEBUG = False
- [Django]-Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT
- [Django]-Timestamp fields in django
1๐
In response to ron_gโs comment in Omid Rahaโs answer:
Consider the case where there are less than 10 records in the list:
Note that this approach
list[:10:-1]
will return an empty list, in contrast to
list[:10][::-1]
which will return all the records in the list, if the total records are less than 10.
- [Django]-How do I check for last loop iteration in Django template?
- [Django]-How to delete a record in Django models?
- [Django]-Pass extra arguments to Serializer Class in Django Rest Framework
-1๐
you can convert the queryset to a list and select the last n elements normally
messages = list(Messages.objects.filter(since=since))
messages = oldMessageis[-n:len(oldMessageis)]
- [Django]-Adding css class to field on validation error in django
- [Django]-Django/DRF โ 405 Method not allowed on DELETE operation
- [Django]-Django: Display Choice Value