python - django queryset runtime - get nth entry in constant time -


i'm using multiple ways data db via different django querysets, know runtime each queryset , if possible better way (to maybe data in constant time!!)

qs = mymodel.objects.order_by('-time') qs = qs.filter(blah = blah) 

to first entry i'm doing this:

entry = list(qs[:1]) first_entry = entry[0] 

or 10th , last entry:

entry = list(qs) some_entry = entry[9] last_entry = entry[-1]  

but believe take o(n) time, there anyway nth term in constant time? dont want use get() dont know id or other value of entry(its sorted), position.

i may use annotate, take o(n) runtime.

mymodel.objects.values('date').annotate(min_value=min('value')).order_by('min_value')[0]  

i know position need entry in constant time?

from docs:

use subset of python’s array-slicing syntax limit queryset number of results. equivalent of sql’s limit , offset clauses.

generally, slicing queryset returns new queryset – doesn’t evaluate query. exception if use “step” parameter of python slice syntax.

to retrieve single object rather list (e.g. select foo bar limit 1), use simple index instead of slice.

https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

the part not evaluating queryset slice important part.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -