Aaron
Aaron

Reputation: 4480

Django retrieve all rows from a table but the last three

I have the last three rows by using Book.objects.order_by('-id')[:3], is there a way to get all the rows excluding those three elements?

Upvotes: 0

Views: 86

Answers (3)

Ravi Kumar
Ravi Kumar

Reputation: 1797

Use:

Book.objects.exclude(pk__in=Book.objects.order_by('-id')[:3])

Note: above query tested on postgres 9.5.3

Upvotes: 0

dmitryro
dmitryro

Reputation: 3506

As you have

books = Book.objects.order_by('-id')[:3]

list_to_exclude = [b.id for b in books]

and then

books_excl = Book.objects.all().exclude(id__in=list_to_exclude)

Upvotes: 0

dnit13
dnit13

Reputation: 2496

This should work,

Book.objects.order_by('-id')[3:]

if you want to get them in order

Book.objects.order_by('-id')[3:][::-1]

Upvotes: 1

Related Questions