Search code examples
pythondjangodjango-viewsdjango-queryset

Need to get the last 3 elements Django-Queryset


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”


Solution

  • 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"