On Wednesday, 1 February 2012 08:34:14 UTC, akaariai wrote:
>
> On Feb 1, 9:36 am, newme <dlli...@gmail.com> wrote: 
> > do you mean that queryset will query database every time i call 
> > user[0]? 
>
> Yes. That is exactly what happens: 
> In [7]: qs[0] 
> Out[7]: <OrganisaatioOsa: THL - Terveyden ja hyvinvoinnin laitos> 
> In [9]: print connection.queries 
> [{'time': '0.011', 'sql': 'SELECT ... FROM "organisaatio_osa" LIMIT 
> 1'}] 
>
> In [10]: qs[0] 
> Out[10]: <OrganisaatioOsa: THL - Terveyden ja hyvinvoinnin laitos> 
> In [11]: print connection.queries 
> [{'time': '0.011', 'sql': 'SELECT ... FROM "organisaatio_osa" LIMIT 
> 1'}, 
>  {'time': '0.001', 'sql': 'SELECT ... FROM "organisaatio_osa" LIMIT 
> 1'}] 
>
> If you do not want this to happen, you can evaluate your queryset into 
> a list first by: 
> objlist = list(qs[0:wanted_limit]) 
> and now objlist is just a regular Python list. 
>
> The lazy evaluation of querysets can be a little surprising sometimes. 
> Using django-debug-toolbar or just settings.DEBUG = True, and then 
> print connection.queries is recommended :) 
>
>  - Anssi


Slight clarification: the slicing will only trigger a db call if the 
queryset has not been evaluated. Converting it to a list is one way of 
doing that, but if you iterate the queryset in any way it will populate the 
internal cache and not call the database on subsequent slices.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/0c4swAOEgygJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to