Best Queryset Practice

51 views
Skip to first unread message

Paritosh Gupta

unread,
Jun 22, 2015, 11:28:51 AM6/22/15
to django...@googlegroups.com
Hello,

Do advice me on:

queryset = User.objects.all()
user = get_object_or_404(pk=id)


> Is it better to call the list in queryset and then apply filter or directly use .filter() in the first step.

> If so, when we call all the object frequently does it cache and from cache we do filter or does it db everytime.

Tim Graham

unread,
Jun 22, 2015, 12:32:40 PM6/22/15
to django...@googlegroups.com

Luis Zárate

unread,
Jun 22, 2015, 3:10:12 PM6/22/15
to django...@googlegroups.com
Querysets are lazy,  so Model.objects.all().filter(...) execute a same query that Model.objects.filter(...).all()  and Model.objects.filter(...).  For check this tray  in shell

str(Model.objects.all().filter(pk=1).query)

str(Model.objects.filter(pk=1).all().query)

str(Model.objects.filter(pk=1).query)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6879eaf6-d906-40ff-8ff1-bed514621856%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
"La utopía sirve para caminar" Fernando Birri


Paritosh Gupta

unread,
Jun 23, 2015, 2:48:45 AM6/23/15
to django...@googlegroups.com
Hey,

Thanks for your prompt reply Tim & luisza14, i have gone through the documentation. From what i have understood:

When we get all objects from the queryset = User.objects.all() it cache the result and it is better to filter it from this result than hitting the db on every subsequent request. while when it does not have desired result it will hit the db and fetch it.

correct me if i am wrong. 


Well let say i have 1 million rows, is it advisable to work this same manner as it will be caching all 1million result?
Reply all
Reply to author
Forward
0 new messages