Need to get the last 3 elements, but each one separately without using loops in Django-Queryset
I try to get elements with use order_by(-id)[:3], but I need to be able to use each of the elements without “for”
CodePudding user response:
Go for this one:
queryset = MyModel.objects.all()
item_minus_3, item_minus_2, item_minus_1 = queryset[len(queryset)-3:]
This is a workaround because "Negative indexing is not supported"
CodePudding user response:
Try this
last_3_elements = list(YourModelName.objects.all().order_by('-id'))[:3] #get the last three id using this
first_element = last_3_elements[0]
second_element = last_3_elements[1]
third_element = last_3_elements[2]