Does .filter on an existing QuerySet hit the database again?

1,016 views
Skip to first unread message

carole...@gmail.com

unread,
Mar 9, 2007, 10:20:12 AM3/9/07
to Django users
I was trying to figure out how exactly caching worked with the query
sets...

If I was running three different queries against the same table like
below, I know it hits the DB each time:

objects = MyObject.objects.fillter(object_name="value")
# some code here

objects = MyObject.objects.fillter(object_name="value2")
# some code here

objects = MyObject.objects.fillter(object_name="value3")
# some code here


If I instead did this, would it reduce DB hits..or does it still hit
the DB for the Query each time?

allobjects = MyObject.objects.all()
objects = allobjects.fillter(object_name="value")
# some code here

objects = allobjects.fillter(object_name="value2")
# some code here

objects = allobjects.fillter(object_name="value3")
# some code here

Thanks for any info! Just trying to optimize things.

Malcolm Tredinnick

unread,
Mar 9, 2007, 10:24:28 AM3/9/07
to django...@googlegroups.com

If you are accessing 'objects' each time, then yes. Basically, a
QuerySet does not do anything (database-wise) until you try to access
one of the result values. At that point it runs the SQL query it is
representing against the database and starts to retrieve the results as
you request them.

Regards,
Malcolm

Malcolm Tredinnick

unread,
Mar 9, 2007, 10:34:53 AM3/9/07
to django...@googlegroups.com

I guess I could also have said that each of the above lines is creating
a new QuerySet, so there is no sharing of results between them. The
"allobjects" line does not access the database, because you aren't using
the results from that QuerySet. But then the first time you create
"objects", it returns a new QuerySet and if you access that variable, it
will talk to the database. The second time you assign to "objects" it
creates another new QuerySet and so on.

Regards,
Malcolm


Reply all
Reply to author
Forward
0 new messages