tags:

views:

273

answers:

1

How would one go about retrieving the last 1,000 values from a database via a Objects.filter? The one I am currently doing is bringing me the first 1,000 values to be entered into the database (i.e. 10,000 rows and it's bringing me the 1-1000, instead of 9000-1,000).

Current Code:

limit = 1000
Shop.objects.filter(ID = someArray[ID])[:limit]

Cheers

+2  A: 

Solution:

(Fourth time lucky!)

queryset = Shop.objects.filter(id=someArray[id])
limit = 1000
count = queryset.count()
endoflist = queryset.order_by('timestamp')[count-limit:]

endoflist is the queryset you want.


Efficiency:

The following is from the django docs about the reverse() queryset method.

To retrieve the ''last'' five items in a queryset, you could do this:

my_queryset.reverse()[:5]

Note that this is not quite the same as slicing from the end of a sequence in Python. The above example will return the last item first, then the penultimate item and so on. If we had a Python sequence and looked at seq[-5:], we would see the fifth-last item first. Django doesn't support that mode of access (slicing from the end), because it's not possible to do it efficiently in SQL.

So I'm not sure if my answer is merely inefficient, or extremely inefficient. I moved the order_by to the final query, but I'm not sure if this makes a difference.

Alasdair
Ahh! You're on the right track, my good man. However I need it to Descend. Therefore if it went 1,2,3,4,5,6,7 and I wanted the last two.. I'd like it as "6,7" and not "7,6".
day_trader
Then how about: `Shop.objects.filter(id=someArray[id]).reverse()[:limit].reverse()`
Dominic Rodger
Doesn't work. That just reverts it back to the original list (first 1000 instead of last.
day_trader
Good job! That works like a dream! Though is that the most efficient way? I'm not too sure how Django handles these calls, but aren't you originally searching for all IDs via timestamp and then doing the limit? As opposed to the original way which limits the original search?
day_trader
I added a little bit to my answer about efficiency, but it's not really my area of expertise.
Alasdair