[Django]-How to return all records but exclude the last item

11πŸ‘

βœ…

For all objects:

Heat.objects.order_by("-created_at")[1:]

For a particular animal it will be:

Heat.objects.filter(animal_id=2).order_by("-created_at")[1:]

where [1:] on a queryset has regular python slice syntax and translates to SQL LIMIT syntax. (In this example it simply removes the first / most recently created element)

Upd: as @schwobaseggl mentioned in his comment, slices with negative indices don’t work on django querysets. Therefore the objects are reverse ordered first.

πŸ‘€Art

4πŸ‘

I just converted your SQL query to Django ORM code.

First, fetch the max created_at value using aggregation and do an exclude.

from django.db.models import Max

heat_objects = Heat.objects.filter(
    animal_id=2
).exclude(
    created_at=Heat.objects.all().aggregate(Max('created_at'))['created_at__max']
)
πŸ‘€anupsabraham

1πŸ‘

Get last record:

obj= Heat.objects.all().order_by('-id')[0]

Make query:

query = Heat.objects.filter(animal_id=2).exclude(id=obj['id']).all()
πŸ‘€Marin

-1πŸ‘

The query would be :

Heat.objects.all().order_by('id')[1:]

You could also put any filter you require by replacing all()

πŸ‘€Pansul Bhatt

Leave a comment