basci question about queryset for retrieving top element

35 views
Skip to first unread message

NENAD CIKIC

unread,
Apr 14, 2012, 12:56:07 PM4/14/12
to Django users
Hello!
I want to get just the top element of one queryset. SO I have
something as
qs=MyModel.objects.filter(...).order_by(..)

and then use qs[0] and check some value

I wonder now if i did the right thing or it is better to use .extra on
queryset.
Is the queryset object allocated for all objects, or is django/python
smarter than me and gets only the needed object?

Should I maybe do directly
topObj=MyModel.objects.filter(...).order_by(..)[0]

What is better?
Thanks
Nenad

Pavan Verma

unread,
Apr 16, 2012, 1:54:50 AM4/16/12
to Django users
I am a Django newbie and also interested in this question.

From reading the Django book http://www.djangobook.com/en/2.0/chapter05/,
I see that the query 'Publisher.objects.order_by('name')[0:2]' maps
to:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
OFFSET 0 LIMIT 2;

Also, Django delays execution of the db query until the result is
actually required.


Given the above two observations, I would think that both the type of
accesses you mentioned will do exactly the same thing, which is to do
a query with "OFFSET 0 LIMIT 1".


To confirm this, you can use the django-devserver (https://github.com/
dcramer/django-devserver) with SQL queries enabled which will display
every query made in real time.

thanks,
-pavan

NENAD CIKIC

unread,
Apr 16, 2012, 11:35:23 PM4/16/12
to Django users
OK, thanks for sharing this

On 16 Apr, 07:54, Pavan Verma <pavan.ve...@gmail.com> wrote:
> I am a Django newbie and also interested in this question.
>
> From reading the Django bookhttp://www.djangobook.com/en/2.0/chapter05/,

HarpB

unread,
Apr 17, 2012, 1:42:10 AM4/17/12
to django...@googlegroups.com
Both patterns will produce same query. You can also use django-debug-toolbar, which gives ur debugsqlshell tool. So you can execute code from the commandline and can see what the query will be.

Django also has a code pattern for your case - for getting the first element, you can just use latest() https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
i.e. Model.objects.latest()

NENAD CIKIC

unread,
Apr 17, 2012, 9:41:30 PM4/17/12
to Django users
OK, thanks
Always learning.
What I miss from my other programming is MSDN like style of help
pages. I tend more and more to use the django pdf documentation
because I can't get used to the web interface for this.

HarpB

unread,
Apr 17, 2012, 10:34:38 PM4/17/12
to django...@googlegroups.com

NENAD CIKIC

unread,
Apr 17, 2012, 11:04:22 PM4/17/12
to Django users
Thanks,
I will check

On 18 Apr, 04:34, HarpB <hsbsi...@gmail.com> wrote:
> Like thishttp://readthedocs.org/docs/django/en/latest/py-modindex.html?highlig...
> or perhaps thishttp://djangoapi.quamquam.org/trunk/?
Reply all
Reply to author
Forward
0 new messages