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.
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
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