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
- [Django]-Asterisk in django forms validation messages
- [Django]-Populate CheckboxSelectMultiple with existing data from django model form
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
- [Django]-Implementing accent insensitive search on django using sqlite
- [Django]-Why is redirection important after dealing with POST data?
- [Django]-Can't get media files in heroku
- [Django]-How can i create Generated/Computed column Postgres/DJANGO?
-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
Source:stackexchange.com